<template>

    <TopNav :isShowTitle="false">
        <template #right>
            <div class="nav_right">
                <el-button size="large" @click="toOrderQuery">订单查询</el-button>
                <el-select :disabled="shoppingCarData[currentActiveVariableIndex].length > 0"
                    popper-class="custom_select" v-model="currentPriceType" placeholder="Select" size="large"
                    style="width: 140px;margin-left: 20px;margin-right: 20px">
                    <el-option v-for="item in allGoodsData" :key="item.priceType" :label="item.priceTypeText"
                        :value="item.priceType" />
                </el-select>
                <OnlineStatus />
                <UserInfo />
            </div>
        </template>

    </TopNav>

    <div class="main_wrap">

        <div class="wrap">
            <div class="left">
                <div class="left_container">
                    <div class="member">

                        <el-input v-if="!currentMemberInfo || !currentMemberIsLogin" class="telphone"
                            v-model="currentTelPhone" size="large" @click="showPhoneKeyboard" placeholder="会员登录,请输入手机号">
                            <template #prefix>
                                <el-icon class="el-input__icon" size="24">
                                    <Avatar />
                                </el-icon>
                            </template>
                        </el-input>
                        <div class="member_info" v-if="currentMemberInfo && currentMemberIsLogin">
                            <div class="top">
                                <div class="flex">
                                    <el-icon class="el-input__icon" size="20" style="margin-right: 5px;">
                                        <Avatar />
                                    </el-icon>

                                    <div>{{ currentMemberInfo.phoneNumber }}</div>
                                </div>
                                <el-button size="large" style="width: 68px;" type="danger" @click="logoutMember">
                                    <SvgIcon name="logout" color="#fff" size="20" style="margin-right: 2px;" />
                                    退出
                                </el-button>
                            </div>
                            <div class="bottom">
                                <div class="left">
                                    <div class="balance">
                                        <span class="label">余额：</span>
                                        <span class="num">{{ NP.plus(currentMemberInfo.capital,
        currentMemberInfo.giveCash)
                                            }}</span>
                                    </div>
                                    <div class="coupon" @click="openCouponDialog">
                                        <span class="label">优惠券：</span>
                                        <span class="num">{{ currentCouponList.length }}<span
                                                style="color:var(--el-color-success)">({{ currentUsableCouponData.length
                                                }})</span></span>
                                    </div>
                                </div>
                                <el-button size="large" type="primary" style="width: 68px;" @click="openRechargeDialog">
                                    <SvgIcon name="money" color="#fff" size="20" style="margin-right: 2px;" />充值
                                </el-button>
                            </div>
                        </div>
                    </div>
                    <div class="btns_group">
                        <el-button type="danger" size="large"
                            :disabled="shoppingCarData[currentActiveVariableIndex].length <= 0"
                            @click="clear">清空</el-button>
                        <el-button type="danger" size="large"
                            :disabled="!currentRow || shoppingCarData[currentActiveVariableIndex].length <= 0"
                            @click="delRow">删除</el-button>
                        <el-button type="primary" size="large" @click="prevCar"
                            :disabled="currentShoppingCarPageNo == 1">上页</el-button>
                        <el-button type="primary" size="large" @click="nextCar"
                            :disabled="currentShoppingCarPageNo >= Math.ceil(shoppingCarData[currentActiveVariableIndex].length / shoppingCarPageSize)">下页</el-button>
                        <el-button type="danger" size="large" style="flex: 0;margin-right: 0" v-if="isShowGiftBtn"
                            @click="openGiftDialog">赠</el-button>
                    </div>
                    <div class="table_wrap" ref="shoppingCarTableRef">
                        <el-table :header-cell-style="{ backgroundColor: 'var(--el-color-primary)', color: '#fff' }"
                            stripe :data="currentTableData" @current-change="handleCurrentChange" highlight-current-row
                            class-name="my_table">

                            <el-table-column type="index" label="序" :index="indexMethod" width="46" />
                            <el-table-column>
                                <template #header>
                                    <div class="table_header">
                                        <div>商品</div>
                                        <div style="max-width: 24.65%;">小计</div>
                                        <div style="text-align:center;max-width: 35.21%">数/重量</div>

                                    </div>
                                </template>
                                <template #default="scope">
                                    <div class="goods_name">

                                        <template v-if="scope.row.isGift">
                                            <el-tag type="danger" size="small" effect="dark"
                                                disable-transitions>赠</el-tag>
                                        </template>
                                        <template
                                            v-if="scope.row.discount && scope.row.discount !== null && scope.row.useUser !== '2'">
                                            <el-tag type="primary" size="small" effect="dark" disable-transitions>{{
        scope.row.discount }}折</el-tag>
                                        </template>
                                        <template
                                            v-if="scope.row.discount === null && scope.row.basicPrice > scope.row.retailPrice && scope.row.useUser !== '2'">
                                            <el-tag type="danger" size="small" effect="dark"
                                                disable-transitions>降</el-tag>
                                        </template>
                                        <template
                                            v-if="(scope.row.discount !== null || scope.row.basicPrice > scope.row.retailPrice) && scope.row.useUser === '2'">
                                            <el-tag type="danger" size="small" effect="dark">会员专享</el-tag>
                                        </template>

                                        {{ scope.row.goodsName }}
                                    </div>
                                    <div class="row">
                                        <div v-if="scope.row.isGift" class="red">
                                            <span style="font-size: 12px;"> &yen;</span>{{ scope.row.basicPrice }}
                                        </div>
                                        <div v-else>
                                            <!--未登录会员 且该商品是会员专享商品 显示原价-->
                                            <div class="red"
                                                v-if="!currentMemberInfo && (scope.row.discount !== null || scope.row.basicPrice > scope.row.retailPrice) && scope.row.useUser === '2'">
                                                <span style="font-size: 12px;"> &yen;</span>{{ scope.row.basicPrice }}
                                                <span style="color:var(--el-color-info)"
                                                    v-show="scope.row.retailPrice !== scope.row.basicPrice">({{
        scope.row.retailPrice }})</span>
                                            </div>
                                            <!--其它情况显示销售价-->
                                            <div class="red" v-else>
                                                <span style="font-size: 12px;"> &yen;</span>{{ scope.row.retailPrice }}
                                                <span style="color:var(--el-color-info)"
                                                    v-show="scope.row.retailPrice !== scope.row.basicPrice">({{
        scope.row.basicPrice }})</span>
                                            </div>
                                        </div>
                                        <!--小计  未登录会员且该商品是会员专享商品 或者是赠品 使用原价计算-->
                                        <div class="red" style="max-width:24.65%"
                                            v-if="scope.row.isGift || (!currentMemberInfo && (scope.row.discount !== null || scope.row.basicPrice > scope.row.retailPrice) && scope.row.useUser === '2')">
                                            <span style="font-size: 12px;"> &yen;</span>{{
        roundNumber(NP.times(scope.row.quantity, scope.row.basicPrice)) }}
                                        </div>
                                        <div class="red" style="max-width:24.65%" v-else>
                                            <span style="font-size: 12px;"> &yen;</span>{{
        roundNumber(NP.times(scope.row.quantity, scope.row.retailPrice)) }}
                                        </div>
                                        <!-- style="max-width:100px" -->
                                        <div style="max-width:35.21%">
                                            <MyInputNumber :isShowControls="scope.row.isQuantityUnit == 'y'"
                                                @inputCount="handleMyInputCount(scope.row)" :count="scope.row.quantity"
                                                @minus="handleMyInputMinus(scope.row)"
                                                @plus="handleMyInputPlus(scope.row)" />

                                        </div>

                                    </div>
                                </template>
                            </el-table-column>

                            <template #empty>
                                <div class="empty_wrap">

                                    <el-empty description="暂未添加商品" :image-size="110" />
                                </div>

                            </template>
                            <!-- <el-table-column prop="goodsName" label="商品" /> -->
                            <!-- <el-table-column prop="num" label="数/重量" width="76" />
                            <el-table-column prop="total" label="小计" header-align="right" align="right">
                                <template #header>
                                    <el-input v-model="search" size="small" placeholder="Type to search" />
                                </template>
                            </el-table-column> -->
                        </el-table>
                    </div>

                    <div class="left_bottom">
                        <div class="total_price">
                            <div class="left">
                                <span v-show="currentTotalActivityDiscount > 0 || currentCouponDiscountPrice > 0"
                                    @click="openActivityDiscountDialog"><i
                                        v-show="currentTotalActivityDiscount > 0">活动优惠：&yen;{{
        currentTotalActivityDiscount }}</i> <i
                                        v-show="currentCouponDiscountPrice > 0">优惠券抵：&yen;{{
        currentCouponDiscountPrice }}</i></span>



                                <div>应收：&yen;{{ computedReceivePrice }}</div>
                            </div>

                            <el-button @click="handleSettlement" type="danger" size="large"
                                :disabled="shoppingCarData[currentActiveVariableIndex].length <= 0">
                                <SvgIcon name="shopping" color="#fff" size="18" style="margin-right: 2px;" />结算
                            </el-button>




                        </div>
                        <!--v1 v2 v3 v4-->
                        <div class="varible_container">
                            <el-badge :value="computedVariableNums(index)" :hidden="shoppingCarData[index].length == 0"
                                class="mark" v-for="(item, index) in 4" :offset="[-20, 10]" :max="99">
                                <div class="item" @click="changeVariable(index)"
                                    :class="{ active: index == currentActiveVariableIndex }">V{{
        item
    }}</div>
                            </el-badge>
                        </div>
                    </div>
                </div>

            </div>
            <div class="right">
                <div class="right_top">
                    <MyInput @click="showSearchKeyboard" placeholder="请输入商品首字母搜索" :innerText="goodsSearchKeywords"
                        class="item" style="width: 100%;" />

                    <!-- <el-input :prefix-icon="Search" @click="showSearchKeyboard" v-model="goodsSearchKeywords"
                        size="large" placeholder="搜索商品" class="item" /> -->
                    <!-- {{ netWeight }} -->
                    <WeightAndTare />
                </div>
                <div class="goods_group">

                    <el-button @click="prevGroup" :disabled="currentActiveGroupPageNo <= 1"
                        v-show="currentActiveGroupPageNo > 1" class="page_btn prev" :icon="ArrowLeftBold"></el-button>

                    <div class="list">

                        <el-button size="large" @click="changeGroup(item, index)"
                            :type="currentActiveGroupName == item ? 'primary' : ''"
                            v-for="(item, index) in currentActiveGroupPaginateData"><span
                                :class="{ active: currentActiveGroupName == item }" class="group_name">{{
        item }}</span></el-button>
                    </div>



                    <el-button @click="nextGroup"
                        :disabled="currentActiveGroupPageNo >= Math.ceil(currentActiveGroupData.flat().length / currentActiveGroupPageSize)"
                        v-show="currentActiveGroupPageNo < Math.ceil(currentActiveGroupData.flat().length / currentActiveGroupPageSize)"
                        class="page_btn next" :icon="ArrowRightBold"></el-button>

                </div>

                <div class="goods_list" ref="goodsListWrapRef" v-if="currentPageData.length > 0">

                    <div v-for="(item) in currentPageData" class="item"
                        :class="{ active: currentSelectGoods.goodsID === item.goodsID }" @click="selectGoods(item)">
                        <div class="goods_name">
                            <template v-if="item.discount !== null && item.useUser !== '2'">
                                <el-tag type="primary" size="small" effect="dark">{{ item.discount }}折</el-tag>
                            </template>
                            <template
                                v-if="item.discount === null && item.basicPrice > item.retailPrice && item.useUser !== '2'">
                                <el-tag type="danger" size="small" effect="dark">降</el-tag>
                            </template>
                            <template
                                v-if="(item.discount !== null || item.basicPrice > item.retailPrice) && item.useUser === '2'">
                                <el-tag type="danger" size="small" effect="dark">会员专享</el-tag>
                            </template>
                            {{ item.goodsName }}
                        </div>
                        <!--未登录会员 且该商品是会员专享商品 显示原价-->
                        <div class="info"
                            v-if="!currentMemberInfo && (item.discount !== null || item.basicPrice > item.retailPrice) && item.useUser === '2'">
                            <span class="price">&yen;{{ item.basicPrice }}</span> / {{ item.saleUnit }}
                        </div>
                        <!--其它情况下显示 销售价-->
                        <div class="info" v-else><span class="price">&yen;{{ item.retailPrice }}</span> / {{
        item.saleUnit }}
                        </div>
                    </div>

                    <el-button v-if="currentPageNo > 1" @click="currentPageNo--" style="height: 100%;">上一页</el-button>
                    <el-button type="primary" v-if="currentPageNo < totalPages" @click="currentPageNo++"
                        style="height: 100%;margin-left: 0;">下一页</el-button>

                </div>
                <div class="empty" v-else>
                    <el-empty description="未搜索到商品，请更换关键字或选择其它分组" />
                </div>
            </div>
        </div>
        <!--搜索键盘-->
        <SearchKeyboard v-model="isShowSearchKeyboard" @onChange="onSearchKeyboardChange"
            keyboardContainerClass="shopsale_searchgoods_id"></SearchKeyboard>
        <!--会员手机号键盘-->
        <PhoneKeyboard :validatePhone="true" v-model="isShowPhoneKeyboard" :inputVal="currentTelPhone"
            @onConfirmPhone="confirmPhone" keyboardContainerClass="shopsale_phonekeyboard_id" />
        <!--数字键盘(输入数量、重量)-->
        <CountKeyboard class="newtransfer_count_keyboard" :placeholder="`请输入${isShowPoint ? '重' : '数'}量`"
            v-model="isShowCountKeyboard" :isShowPoint="isShowPoint"
            keyboardContainerClass="newtransfer_count_container" @onConfirm="onConfirmCountOrWeight"
            ref="shopSaleCountKeboardRef" :title="`${currentRow?.goodsName}`" />

        <!--未注册会员弹窗-->
        <el-dialog v-model="registerMemeberDialogVisible" :before-close="cancelRegisterMemeber" title="提示" width="400">
            <span>当前号码未注册会员，是否立即注册？</span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="cancelRegisterMemeber">取消</el-button>
                    <el-button size="large" type="primary" @click="confirmRegisterMemeber">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!--会员充值弹窗-->
        <el-dialog v-model="rechargeDialogVisible" class="recharge_dialog" :show-close="false" title="会员充值" width="800">
            <template #header="{ close, titleId, titleClass }">
                <div class="my-header" style="display: flex;align-items: center;justify-content: space-between;">
                    <div style="font-size: 20px">会员充值</div>
                    <el-button size="large" type="primary" @click="toRechargeLog">
                        充值记录
                    </el-button>
                </div>
            </template>
            <el-descriptions size="large" title="">
                <el-descriptions-item label="会员号码">{{ currentMemberInfo?.phoneNumber }}</el-descriptions-item>
                <el-descriptions-item label="优惠券">
                    <el-tag size="small">{{ currentCouponList.length }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="会员余额" v-if="currentMemberInfo">{{ NP.plus(currentMemberInfo.allCapital,
        currentMemberInfo.allGiveCash)
                    }} (当前店铺可用：{{ NP.plus(currentMemberInfo.capital, currentMemberInfo.giveCash)
                    }})</el-descriptions-item>

            </el-descriptions>
            <el-divider style="margin:0 0 10px 0;" />
            <div class="activity_list">
                <div class="item" @click="onSelectActiity(item, index)"
                    :class="{ active: currentRechargeActivityIndex === index }"
                    v-for="(item, index) in rechargeActivityList">
                    <div class="capital">充值{{ item.capital }}元</div>
                    <div class="desc">{{ item.explain }}</div>
                </div>

            </div>
            <div class="pay_type">
                <el-button size="large" type="primary" @click="confirmRecharge(0)">
                    现金支付
                </el-button>
                <el-button size="large" type="success" @click="confirmRecharge(1)">
                    电子支付
                </el-button>
                <!-- <el-button size="large" type="warning" @click="confirmRecharge(2)">
                    银联支付
                </el-button> -->
            </div>
            <!-- <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="cancelRegisterMemeber">取消</el-button>
                    <el-button size="large" type="primary" @click="confirmRegisterMemeber">
                        确认
                    </el-button>
                </div>
            </template> -->
        </el-dialog>
        <!--确认现金充值弹窗-->
        <el-dialog v-model="cashRechargeDialogVisible" title="确认现金充值?" width="500">
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="cashRechargeDialogVisible = false">取消</el-button>
                    <el-button size="large" type="primary" @click="confirmCashRecharge">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!--电子支付充值弹窗-->
        <el-dialog :close-on-click-modal="false" v-model="electronicRechargeDialogVisible" :show-close="false"
            title="会员充值电子支付" width="800">
            <div class="electronic_recharge_dialog_main" v-if="electronicRechargeDialogVisible">
                <div class="row">请使用扫码枪扫描付款码</div>
                <div class="row money">
                    金额 <span style="color:var(--el-color-danger)">&yen;{{
        rechargeActivityList[currentRechargeActivityIndex].capital }}</span>
                </div>


                <el-progress :percentage="100" :show-text="false" :indeterminate="true" :duration="5" />
                <div class="row wait">
                    等待支付中...
                </div>


            </div>
            <template #footer>
                <div class="dialog-footer">

                    <el-button size="large" @click="electronicRechargeDialogVisible = false">取消</el-button>
                </div>
            </template>
        </el-dialog>


        <!--优惠券弹窗-->
        <el-dialog v-model="couponDialogVisible" :title="`共${currentCouponList.length}张优惠券`" width="900">
            <div class="copon_dialog_main">
                <div class="title">可使用优惠券({{ pageUsableCouponData.flat().length }})张</div>
                <div class="usable_coupon_wrap">
                    <el-button @click="currentUsableCouponPageNo--" :disabled="currentUsableCouponPageNo <= 1"
                        v-show="currentUsableCouponPageNo > 1" class="page_btn prev" :icon="ArrowLeftBold"></el-button>
                    <div class="usable_coupon_list">
                        <div class="coupon_item"
                            :class="{ active: item.memberCouponID === currentSelectCoupon?.memberCouponID || '' }"
                            v-for="item in pageUsableCouponData[currentUsableCouponPageNo - 1]"
                            @click="chooseCoupon(item)">
                            <div class="left">
                                <div class="discount_text">{{ item.discountText }}</div>
                                <div class="type_text">{{ item.typeText }}</div>
                            </div>
                            <div class="right">
                                <div>{{ item.useName }}</div>
                                <div class="time">有效期至{{ item.endUseTime }}</div>
                            </div>
                        </div>

                    </div>

                    <el-button @click="currentUsableCouponPageNo++"
                        :disabled="currentUsableCouponPageNo >= Math.ceil(pageUsableCouponData.flat().length / currentUsableCouponPageSize)"
                        v-show="currentUsableCouponPageNo < Math.ceil(pageUsableCouponData.flat().length / currentUsableCouponPageSize)"
                        class="page_btn next" :icon="ArrowRightBold"></el-button>
                </div>

                <div class="title">不可使用优惠券({{ pageUnusableCouponData.flat().length }})张</div>
                <div class="unusable_coupon_wrap">
                    <el-button @click="currentUnusableCouponPageNo--" :disabled="currentUnusableCouponPageNo <= 1"
                        v-show="currentUnusableCouponPageNo > 1" class="page_btn prev"
                        :icon="ArrowLeftBold"></el-button>

                    <div class="unusable_coupon_list">

                        <div class="coupon_item"
                            :class="{ active: item.memberCouponID === currentSelectCoupon?.memberCouponID || '' }"
                            v-for="item in pageUnusableCouponData[currentUnusableCouponPageNo - 1]">

                            <div class="left">
                                <div class="discount_text">{{ item.discountText }}</div>
                                <div class="type_text">{{ item.typeText }}</div>
                            </div>
                            <div class="right">
                                <div>{{ item.useName }}</div>
                                <div class="time">有效期至{{ item.endUseTime }}</div>
                            </div>
                        </div>

                    </div>

                    <el-button @click="currentUnusableCouponPageNo++"
                        :disabled="currentUnusableCouponPageNo >= Math.ceil(pageUnusableCouponData.flat().length / currentUnusableCouponPageSize)"
                        v-show="currentUnusableCouponPageNo < Math.ceil(pageUnusableCouponData.flat().length / currentUnusableCouponPageSize)"
                        class="page_btn next" :icon="ArrowRightBold"></el-button>
                </div>

            </div>

            <template #footer>
                <div class="dialog-footer">

                    <el-button size="large" @click="clearCoupon" type="warning"
                        :disabled="!currentSelectCoupon">清除券</el-button>
                    <el-button size="large" @click="couponDialogVisible = false">取消</el-button>
                    <el-button size="large" type="primary" @click="confrimSelectCoupon">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!--赠品弹窗-->

        <el-dialog v-model="giftDialogVisible" title="请选择赠品" width="900">
            <div class="gift_dialog_main">
                <div v-for="parentItem in currentGoodsGiftAndActivitys" :key="parentItem.activity.activityID">
                    <div class="activity_name">
                        <!-- <el-radio  v-model="currentGiftActivityID"  :value="parentItem.activity.activityID" size="large">
                            {{ parentItem.activity.activityName }}
                        </el-radio>   -->
                        {{ parentItem.activity.activityName }}
                    </div>
                    <div class="goods_wrap">
                        <!-- v-show="parentItem.currentPage > 1" -->
                        <el-button @click="parentItem.currentPage--" :disabled="parentItem.currentPage <= 1"
                            class="page_btn prev" :icon="ArrowLeftBold"></el-button>

                        <div class="goods_list">
                            <el-button size="large" @click="chooseGift(item, index)"
                                :type="currentSelectGoodsGift?.activityGoodsGiftID === item.activityGoodsGiftID ? 'primary' : ''"
                                v-for="(item, index) in pageGiftData(parentItem.giftDescArr)[parentItem.currentPage - 1]"
                                :key="item.pkey" :class="{ active: currentPayType?.pkey === item.pkey }" class="item">{{
        item.goodsName }}*{{ item.quantity }}</el-button>
                        </div>
                        <!-- v-show="parentItem.currentPage < Math.ceil(parentItem.giftDescArr.length / 3)" -->
                        <el-button @click="parentItem.currentPage++"
                            :disabled="parentItem.currentPage >= Math.ceil(parentItem.giftDescArr.length / 3)"
                            class="page_btn next" :icon="ArrowRightBold"></el-button>
                    </div>
                </div>

            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="giftDialogVisible = false">取消</el-button>
                    <el-button size="large" type="primary" @click="confirmChooseGift">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!--活动优惠明细弹窗-->

        <el-dialog v-model="activityDiscountDialogVisible" title="优惠明细" width="900">
            <div class="activity_discount_dialog_main">
                <!-- {{ currentActivityDiscountData }} -->
                <!-- <div v-for="item in currentActivityDiscountData">
                    <span>活动名称:{{ item.activity.activityName }}</span>
                    <span>适用商品:
                        <span v-for="goods in item.goods">
                            {{ goods.goodsName }}
                        </span>
                    </span>
                </div> -->
                <div class="">
                    <el-table stripe :data="currentActivityDiscountData" show-overflow-tooltip highlight-current-row
                        class-name="my_table">
                        <el-table-column type="index" label="序" width="46" />
                        <el-table-column prop="type" label="优惠类型" width="110" />
                        <el-table-column prop="text" label="优惠规则" />
                        <el-table-column label="适用商品">
                            <template #default="scope">
                                [{{ scope.row.goods.map(item => item.goodsName).join('、') }}]
                            </template>
                        </el-table-column>
                        <el-table-column prop="discountPrice" width="110" label="当前优惠(元)" />
                    </el-table>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">

                    <el-button size="large" type="primary" @click="activityDiscountDialogVisible = false">
                        确认
                    </el-button>
                </div>
            </template>

        </el-dialog>
        <!--确认删除行弹窗-->
        <el-dialog v-model="delRowDialogVisible" :show-close="false" title="确认删除？" width="600">
            <div style="margin-bottom:16px">
                {{ currentRow?.goodsName }}
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="delRowDialogVisible = false">取消</el-button>
                    <el-button size="large" type="primary" @click="confirmDelRow">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!--确认清空弹窗-->
        <el-dialog v-model="clearDialogVisible" :show-close="false" title="提示" width="600">
            <div style="margin-bottom:16px">
                确认删除当前订单？
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="clearDialogVisible = false">取消</el-button>
                    <el-button size="large" type="primary" @click="confirmClear">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!--结算弹窗-->
        <PayKeyboard @dialogOpened="payDialogOpened" :layout="payLayout" @onKeyPress="onPayKeyboardKeyPress"
            v-model="isShowPayKeyboard" keyboardContainerClass="pay_keboard_class" @onChange="onPayKeyboardChange"
            :isDisabled="isPayKeyboardDisabled" ref="payKeboardRef">
            <template #top>
                <div class="pay_top">
                    <div class="left">
                        <div class="row">
                            <span>订单金额</span>
                            <div>{{ computedReceivePrice }}</div>
                        </div>
                        <div class="row">
                            <span>未付</span>
                            <div style="color:var(--el-color-danger)">{{ computedUnreceivePrice }}</div>
                        </div>
                        <div class="row">
                            <span>找零</span>
                            <div>{{ computedGiveChange }}</div>
                        </div>
                    </div>
                    <div class="right">
                        <MyInput placeholder="请扫描购物卡或输入购物卡号码" :innerText="currentShoppingCardNo" style="flex: 1"
                            v-if="currentPayType?.pkey === 'OP_GC'"></MyInput>
                        <MyInput placeholder="请输入金额" :innerText="currentPayInput" style="flex: 1"
                            :class="{ select: isPayInputSelect }" @click="isPayInputSelect = false" v-else></MyInput>

                        <el-button @click="confirmPayInput" style="margin-left: 10px;width: 114px;" type="primary"
                            size="large">
                            确定
                        </el-button>
                    </div>
                </div>
            </template>
            <template #left>
                <div class="pay_left">
                    <div class="table_wrap">
                        <!-- :header-cell-style="{ backgroundColor: 'var(--ev-c-black)', color: '#fff' }" -->
                        <el-table border stripe :data="payTypeTable" class-name="my_table">
                            <el-table-column type="index" label="序" :index="payIndexMethod" width="50" />
                            <el-table-column prop="pvalue" label="支付方式" width="190" class-name="custom_paytype">
                                <template #default="scope">
                                    <div v-if="scope.row.isShoppingCard">
                                        <span>{{ scope.row.pvalue }}</span> <span>({{ scope.row.shoppingCardID
                                            }})</span>
                                    </div>
                                    <div v-else>
                                        {{ scope.row.pvalue }}
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="金额" class-name="custom_payamount">
                                <template #default="scope">
                                    <div v-if="scope.row.isShoppingCard">
                                        <span>{{ scope.row.payAmount }}</span> <span>(余额:{{ scope.row.cardBalance
                                            }})</span>
                                    </div>
                                    <div v-else>
                                        {{ NP.plus(scope.row.payAmount, scope.row.giveCash || 0) }}
                                    </div>

                                </template>
                            </el-table-column>

                            <el-table-column label="操作" align="center" width="100">
                                <template #default="scope">

                                    <el-button type="danger" size="large" @click="delPayTypeRow(scope.$index)">
                                        删除
                                    </el-button>

                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </template>
            <template #bottom>
                <div class="pay_type_wrap">

                    <el-button @click="currentPayTypePageNo--" :disabled="currentPayTypePageNo <= 1"
                        v-show="currentPayTypePageNo > 1" class="page_btn prev" :icon="ArrowLeftBold"></el-button>

                    <div class="pay_type_list">

                        <el-button size="large" @click="changePayType(item, index)"
                            :type="currentPayType?.pkey === item.pkey ? 'primary' : ''"
                            v-for="(item, index) in currentPayTypeData[currentPayTypePageNo - 1]" :key="item.pkey"
                            :class="{ active: currentPayType?.pkey === item.pkey }" class="item">{{
        item.pvalue }}</el-button>
                    </div>
                    <el-button @click="currentPayTypePageNo++"
                        :disabled="currentPayTypePageNo >= Math.ceil(currentPayTypeData.flat().length / payTypePageSize)"
                        v-show="currentPayTypePageNo < Math.ceil(currentPayTypeData.flat().length / payTypePageSize)"
                        class="page_btn next" :icon="ArrowRightBold"></el-button>
                </div>
            </template>


        </PayKeyboard>
        <!--重量单位商品选择弹窗-->
        <el-dialog v-model="isShowSelectGoodsDialog" :show-close="false" width="500">
            <template #header>
                <h1 class="selectgoods_dialog_title">{{ currentSelectGoods?.goodsName }}</h1>
            </template>
            <div class="selectgoods_dialog_main">
                <div class="flex">
                    <div class="label">净重</div>
                    <div style="color:var(--el-color-success)">{{ weight }}</div>
                </div>
                <div class="flex">
                    <div class="label">皮重</div>
                    <div style="color:var(--el-color-danger)">{{ tare }}</div>
                </div>
                <div class="flex">
                    <div class="label">单价</div>
                    <!--未登录会员 且该商品是会员专享商品 显示原价-->
                    <div v-if="currentSelectGoods">
                        <div
                            v-if="!currentMemberInfo && (currentSelectGoods.discount !== null || currentSelectGoods.basicPrice > currentSelectGoods.retailPrice) && currentSelectGoods.useUser === '2'">
                            {{ currentSelectGoods.basicPrice }}</div>
                        <!--其它情况下显示 销售价-->
                        <div v-else>{{ currentSelectGoods.retailPrice }}</div>
                    </div>
                </div>
                <div class="flex" v-if="currentSelectGoods">
                    <div class="label">小计</div>
                    <div
                        v-if="!currentMemberInfo && (currentSelectGoods.discount !== null || currentSelectGoods.basicPrice > currentSelectGoods.retailPrice) && currentSelectGoods.useUser === '2'">
                        {{ roundNumber(NP.times(currentSelectGoods.basicPrice, weight)) }}</div>
                    <div v-else>{{ roundNumber(NP.times(currentSelectGoods.retailPrice, weight)) }}</div>

                </div>
            </div>
            <template #footer>
                <div class="selectgoods_dialog_footer">
                    <el-button size="large" @click="isShowSelectGoodsDialog = false">
                        取消
                    </el-button>
                    <el-button size="large" type="primary" @click="confirmSelectGoods">
                        确定
                    </el-button>
                </div>
            </template>

        </el-dialog>

        <!--电子支付、会员支付 弹窗-->
        <el-dialog v-model="isShowElectronicDialog" :title="currentPayType?.pvalue" width="900">
            <div class="electronic_dialog_main">
                <div class="row">请使用扫码枪扫描付款码</div>
                <!--会员支付时 金额=本金+赠金-->
                <!-- <div class="row money" v-if="currentPayType && currentPayType.pkey && payTypeTable && payTypeTable[0]">
                    金额

                    <span style="color:var(--el-color-danger)">&yen;{{ currentPayType.pkey === 'MB' ?
        NP.plus(payTypeTable[0].payAmount, payTypeTable[0].giveCash
            || 0) : payTypeTable[0].payAmount
                        }}</span>2502270009300044
                        
                </div> -->

                <el-progress :percentage="100" :show-text="false" :indeterminate="true" :duration="5" />
                <div class="row wait">
                    扫码完成前请不要关闭此窗口,等待支付中...
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">

                    <el-button size="large" type="primary" @click="isShowElectronicDialog = false">
                        关闭
                    </el-button>
                </div>
            </template>

        </el-dialog>

        <!--创建订单打印wrap-->
        <!--临时添加样式方便调试  style="z-index:1;transform:scale(0.3)"-->
        <div ref="createOrderPrintRef" class="print_wrap" :class="(currentScaleType=='2'||currentScaleType=='3') ? 'tuoliduo' : ''"
            v-if="payTicketInfo" :style="{ paddingLeft: paperLeft, paddingRight: paperRight }">
            <div class="title">欢迎光临[一手店]</div>
            <div>单号：{{ payTicketInfo.orderNO }}</div>
            <div>店铺：{{ shopInfo.shopName }}</div>
            <div>电话：{{ userInfo.user_account }}</div>
            <div>收银：{{ userInfo.user_name }}</div>
            <div>时间：{{ getTimeString(currentTime) }}</div>
            <svg id="barcode"></svg>

            <div class="line"></div>
            <div class="flex">
                <div>商品/单价/数量</div>
                <div>金额</div>
            </div>
            <div class="item" v-for="item in payTicketInfo.reqData?.orderDetailAddDtos"
                :key="item.goodsID + '_' + item.currentTime">
                <div><span class="gift" v-if="item.isGift == 1">【赠】</span>{{ item.goodsName }}</div>

                <div class="flex"
                    v-if="item.retailPrice < item.basicPrice && item.useUser === '2' && !currentMemberInfo">
                    <div>{{ item.basicPrice }} x{{ item.quantity }}</div>
                    <div>¥{{ roundNumber(NP.times(item.basicPrice, item.quantity)) }}</div>
                </div>
                <div class="flex" v-else>
                    <div>{{ item.retailPrice }} x{{ item.quantity }}</div>
                    <div>¥{{ roundNumber(NP.times(item.retailPrice, item.quantity)) }}</div>
                </div>

                <div class="discount" v-if="item.priceActivityID && item.priceTypeActivityDiscount > 0">(原价{{
        item.originalPrice }}
                    已优惠{{
        item.priceTypeActivityDiscount
    }})</div>
            </div>
            <div class="line"></div>
            <div class="flex">
                <div>件数合计</div>
                <div>{{ computedVariableNums(currentActiveVariableIndex) }}</div>
            </div>
            <div class="flex">
                <div>订单金额</div>
                <div>¥{{ orderTotalPrice }}</div>
            </div>

            <div class="flex" v-if="currentTotalActivityDiscount && currentTotalActivityDiscount > 0">
                <div>订单优惠</div>
                <div>¥{{ currentTotalActivityDiscount }}</div>
            </div>
            <div class="flex" v-if="currentCouponDiscountPrice && currentCouponDiscountPrice > 0">
                <div>优惠券抵扣</div>
                <div>¥{{ currentCouponDiscountPrice }}</div>
            </div>

            <div class="flex">
                <div>应收金额</div>
                <div>¥{{ computedReceivePrice }}</div>
            </div>
            <div class="line"></div>
            <div>支付方式</div>
            <div class="flex" v-for="item in payTicketInfo.reqData?.orderPayDto.orderPayAddDtos" :key="item.payType">
                <div>{{ item.payTypeText }}</div>
                <div>¥{{ NP.plus(item.payAmount, item.giveCash || 0) }}</div>
            </div>
            <div class="line"></div>



            <div v-if="currentMemberInfo">
                <div class="flex">
                    <div>会员消费</div>
                    <div>¥{{ memberFee }}</div>
                </div>
                <div class="flex">
                    <div>会员余额</div>
                    <div>{{ payTicketInfo.sumRemainingBalance }}</div>
                </div>
            </div>
            <div class="line"></div>
            <div
                v-if="payTicketInfo.reqData?.orderPayDto.orderPayAddDtos.findIndex(item => item.payType == SHOPPINGCARDKEY) != -1">
                <div>购物卡消费</div>
                <div class="flex"
                    v-for="item in payTicketInfo.reqData?.orderPayDto.orderPayAddDtos.filter(childItem => childItem.shoppingCardID)">
                    <div>购物卡</div>
                    <div>¥{{ item.payAmount }}</div>
                </div>
            </div>
            <div
                v-if="payTicketInfo && payTicketInfo.remainingShoppingCardVos && payTicketInfo.remainingShoppingCardVos.length > 0">
                <div>购物卡余额</div>
                <div class="flex" v-for="item in payTicketInfo.remainingShoppingCardVos">
                    <div>购物卡</div>
                    <div>¥{{ item.cardBalance }}</div>
                </div>
            </div>


            <div class="line"></div>
            <div>多谢惠顾，欢迎下次光临</div>
            <div>客服电话：4006365999</div>
            <div class="margin_bottom_placeholder"></div>
        </div>
        <!--会员充值打印wrap-->
        <div ref="rechargePrintRef" class="print_wrap" :class="currentScaleType == '2' ? 'tuoliduo' : ''"
            style="padding-left:10px" :style="{ paddingLeft: paperLeft, paddingRight: paperRight }">
            <div class="title">一手店会员充值</div>
            <div>单号：{{ rechargeTicketInfo.orderNO }}</div>
            <div>店铺：{{ shopInfo.shopName }}</div>
            <div>电话：{{ userInfo.user_account }}</div>
            <div>收银：{{ userInfo.user_name }}</div>
            <div>时间：{{ getTimeString(currentTime) }}</div>

            <div class="line"></div>
            <div class="flex">
                <div>会员充值</div>
                <div>&yen;{{ rechargeTicketInfo.reqData?.capital }}</div>
            </div>
            <div class="flex">
                <div>赠送金额</div>
                <div>&yen;{{ rechargeTicketInfo.reqData?.giveCash }}</div>
            </div>
            <div class="line"></div>
            <div class="flex">
                <div>支付方式</div>
                <div>{{ rechargeTicketInfo.payType }}</div>
            </div>
            <div class="flex">
                <div>会员号码</div>
                <div>{{ currentMemberInfo?.phoneNumber }}</div>
            </div>
            <div class="flex">
                <div>会员余额</div>
                <div>¥{{ NP.plus(currentMemberInfo?.capital || 0,
                    currentMemberInfo?.giveCash || 0) }}</div>
            </div>
            <div class="line"></div>
            <div>多谢惠顾，欢迎下次光临</div>
            <div>客服电话：4006365999</div>
            <div class="margin_bottom_placeholder"></div>
        </div>
    </div>
</template>

<script setup lang='ts'>

// @ts-nocheck
import { v4 as uuidv4 } from 'uuid';
import domtoimage from 'dom-to-image'; //dom转图片
import JsBarcode from 'jsbarcode'; //条形码
import OnlineStatus from '../components/OnlineStatus.vue'
import NP from "number-precision";
import { ElMessage, ElMessageBox } from 'element-plus'
import { memberLogin, memberRegister, getMemberCoupon, getRechargeActivity, cashRecharge, createOrder, getMemberInfoByCode, getShoppingCardBalance } from '@renderer/api/shopsale'
import pinyin from "pinyin";
import { ref, computed, watch, onMounted, onActivated, onDeactivated, nextTick, toRefs, onBeforeUnmount } from 'vue'
import { useUserStore } from '@renderer/store/user'
import { storeToRefs } from 'pinia'
import { ElTable } from 'element-plus'
import { Avatar, Search, ArrowLeftBold, ArrowRightBold } from '@element-plus/icons-vue'
import { paginateData, getTimeString, getDateTimeString, debounce } from '@renderer/utils'

import MyInputNumber from '@renderer/components/MyInputNumber.vue'
import CountKeyboard from '@renderer/components/CountKeyboard.vue'
import WeightAndTare from '@renderer/components/WeightAndTare.vue'
import GoBack from '@renderer/components/GoBack.vue';
import SearchKeyboard from '@renderer/components/SearchKeyboard.vue'
import PhoneKeyboard from '@renderer/components/PhoneKeyboard.vue'
import PayKeyboard from '@renderer/components/PayKeyboard.vue'

import SvgIcon from '@renderer/components/SvgIcon.vue';
import router from '@renderer/router';
import { dataType } from 'element-plus/es/components/table-v2/src/common';
//定义加减乘除函数
function plus(...args) {
    return NP.plus(...args)
}
function minus(...args) {
    return NP.minus(...args)
}
function times(...args) {
    return NP.times(...args)
}

function divide(...args) {
    return NP.divide(...args)
}


//非价格类型优惠总合
const unPriceTypeDiscountTotal = ref(0)



const SHOPPINGCARDKEY = 'OP_GC'
const isPayKeyboardDisabled = computed(() => !currentPayType.value)
//商品分组
const currentActiveGroupPageNo = ref(1)
const currentActiveGroupPageSize = ref(10)
const currentActiveGroupData = computed(() => {
    return paginateData(currentPriceTypeGoodsData.value.map(data => data.panelType), currentActiveGroupPageSize.value) || []

})

const currentActiveGroupPaginateData = computed(() => {
    return currentActiveGroupData.value[currentActiveGroupPageNo.value - 1]

})

//商品分组上一页下一页
function prevGroup() {

    currentActiveGroupPageNo.value--
}
function nextGroup() {

    currentActiveGroupPageNo.value++
}

const rechargeAuthCode = ref(null) //充值付款码
const rechargeTicketInfo = ref({}) //充值小票需要的数据
const cashRechargeDialogVisible = ref(false) //确认现金充值弹窗
const electronicRechargeDialogVisible = ref(false) //电子支付充值弹窗
const isShowElectronicDialog = ref(false) //是否显示电子支付、会员支付弹窗
const authCode = ref(null) //付款码
const payTicketInfo = ref({}) //结算创建订单 小票需要的数据

const isShowSelectGoodsDialog = ref(false) //重量选择商品弹窗

const createOrderPrintRef = ref()
const rechargePrintRef = ref()
//console.log(createOrderPrintRef)
const offlineUnusablePayTypeList = ref(['EP', 'MB', 'OP_GC']) //离线模式不可使用的支付方式('电子支付\会员支付、购物卡')
const electronicPayTypeList = { "PAT_WC": '微信', "PAT_A": '支付宝', "PAT_UP": '云闪付' } //电子支付方式
const activityTypeObj = {
    '1': '金额满减',
    '2': '件数满减',
    '3': '阶梯金额满减',
    '4': '阶梯件数满减',
    '5': '满额折扣',
    '6': '满件折扣',
    '7': '阶梯金额折扣',
    '8': '阶梯件数折扣',
    '9': '价格直降',
    '10': '价格折扣',
    '11': '赠品'

}
//购物卡
const currentShoppingCardNo = ref('')
//当前输入金额
const currentPayInput = ref('')
const couponDialogVisible = ref(false) //优惠券弹窗
const selectCoupon = ref([null, null, null, null])
const currentSelectCoupon = computed({ //当前使用的优惠券 ref(null) //当前选中的优惠券
    get() {
        return selectCoupon.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        selectCoupon.value[currentActiveVariableIndex.value] = newVal
    }
})


const usingCoupon = ref([null, null, null, null])
const currentUsingCoupon = computed({ //当前使用的优惠券
    get() {
        return usingCoupon.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        usingCoupon.value[currentActiveVariableIndex.value] = newVal
    }
})

const giftDialogVisible = ref(false)//赠品弹窗
const selectGoodsGift = ref([null, null, null, null])
const currentSelectGoodsGift = computed({ ////当前选择的赠品
    get() {
        return selectGoodsGift.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        selectGoodsGift.value[currentActiveVariableIndex.value] = newVal
    }
})





const isShowCountKeyboard = ref(false) //是否显示数字键盘
const isShowPoint = ref(true) //是否显示键盘小数点
const goodsSearchKeywords = ref('')
const newWeight = ref('0.000')
const tareWeight = ref('0.000')
const userStore = useUserStore()
const priceTyleList = ref(['RP', 'RP', 'RP', 'RP'])//价格类型默认零售价
const currentPriceType = computed({
    get() {
        return priceTyleList.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        priceTyleList.value[currentActiveVariableIndex.value] = newVal
    }
})
const pageSize = ref(30)  //分页页码
const goodsListWrapRef = ref()
const telPhone = ref(['', '', '', ''])
const currentTelPhone = computed({
    get() {
        return telPhone.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        telPhone.value[currentActiveVariableIndex.value] = newVal
    }
})
const isShowSearchKeyboard = ref(false)
const isShowPhoneKeyboard = ref(false)
const memeberInfo = ref([null, null, null, null])
const currentMemberInfo = computed({
    get() {
        return memeberInfo.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        memeberInfo.value[currentActiveVariableIndex.value] = newVal
    }
})

const memberIsLogin = ref([false, false, false, false])
const currentMemberIsLogin = computed({
    get() {
        return memberIsLogin.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        memberIsLogin.value[currentActiveVariableIndex.value] = newVal
    }
})

const registerMemeberDialogVisible = ref(false)
const couponList = ref([[], [], [], []])
const currentCouponList = computed({//当前会员所有优惠券列表
    get() {
        return couponList.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        couponList.value[currentActiveVariableIndex.value] = newVal
    }
})
const currentRechargeActivityIndex = ref('') //当前充值活动索引
const rechargeDialogVisible = ref(false)
const rechargeActivityList = ref([]) //充值活动列表
const { userInfo, shopInfo, weight, tare, allData, saleGoodsData, shoppingCarData, payTypeList, quickPayList, currentTime, currentActiveVariableIndex, isOnline, paperLeft, paperRight, currentScaleType } = storeToRefs(userStore)
const saleOrganizationID = userInfo.value.user_organizationId
const shopID = shopInfo.value.shopID
const shopName = shopInfo.value.shopName

const allGoodsData = computed(() => allData.value.goodsInfos)
const priceActivitys = computed(() => allData.value.priceActivitys) //价格类型活动
const otherActivitys = computed(() => allData.value.otherActivitys) //非价格类型活动
const discountStep = computed(() => allData.value.discountStep) //阶梯折扣活动规则明细
const couponsForShop = computed(() => allData.value.coupons) //当前店可用的优惠券
const deliverCouponsForShop = computed(() => allData.value.deliverCoupons) //当前店可发放的优惠券
const createOrderDeliverCoupons = computed(() => deliverCouponsForShop.value.filter(item => item.type === '2'))   //订单创建成功后可发的券 type为2
const goodsGift = computed(() => allData.value.goodsGift) //赠品活动规则明细
const goodsGiftAndActivitys = ref([[], [], [], []])
const currentGoodsGiftAndActivitys = computed({  //当前订单满足的赠品以及赠品活动
    get() {
        return goodsGiftAndActivitys.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        //console.log(newVal)
        goodsGiftAndActivitys.value[currentActiveVariableIndex.value] = newVal
    }
})

const usableCouponData = ref([[], [], [], []]) //
const currentUsableCouponData = computed({  //当前可用优惠券
    get() {
        return usableCouponData.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        usableCouponData.value[currentActiveVariableIndex.value] = newVal
    }
})
const couponDiscountPrice = ref([0, 0, 0, 0])
const currentCouponDiscountPrice = computed({  //ref(0) //当前优惠券优惠金额
    get() {
        return couponDiscountPrice.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        couponDiscountPrice.value[currentActiveVariableIndex.value] = newVal
    }
})
const usableCouponPageNo = ref([1, 1, 1, 1])
const currentUsableCouponPageNo = computed({  //当前可用优惠券 当前页
    get() {
        return usableCouponPageNo.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        usableCouponPageNo.value[currentActiveVariableIndex.value] = newVal
    }
})
const currentUsableCouponPageSize = ref(4) //每页条数

const activityDiscountDialogVisible = ref(false) //活动优惠明细弹窗

const activityDiscountData = ref([[], [], [], []]) //活动优惠明细数据
const currentActivityDiscountData = computed({
    get() {
        //console.log('get~')
        return activityDiscountData.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        //console.log('currentActivityDiscountData变化了')
        //console.log(newVal)
        activityDiscountData.value[currentActiveVariableIndex.value] = newVal
    }
})


//console.log(currentActivityDiscountData.value)

const unusableCouponData = ref([[], [], [], []])
const currentUnusableCouponData = computed({ //当前不可用优惠券
    get() {
        return unusableCouponData.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        unusableCouponData.value[currentActiveVariableIndex.value] = newVal
    }
})
const unusableCouponPageNo = ref([1, 1, 1, 1])
const currentUnusableCouponPageNo = computed({
    get() {
        return unusableCouponPageNo.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        unusableCouponPageNo.value[currentActiveVariableIndex.value] = newVal
    }
})
const currentUnusableCouponPageSize = ref(2) //每页条数
//可用优惠券 分页后的数据
const pageUsableCouponData = computed(() => {
    return paginateData(currentUsableCouponData.value, currentUsableCouponPageSize.value) || []

})
//不可用 优惠券 分页后的数据
const pageUnusableCouponData = computed(() => {
    return paginateData(currentUnusableCouponData.value, currentUnusableCouponPageSize.value) || []


})
const payTypeTable = ref([]) //支付方式列表table
const payKeboardRef = ref()

//充值记录
function toRechargeLog() {

    router.push({ name: 'rechargequery', query: { phone: currentMemberInfo.value.phoneNumber } })
}


//点击会员登录
function showPhoneKeyboard() {

    if (currentPriceType.value !== 'RP') {
        ElMessage({
            message: '非零售价格体系,不能登录会员',
            type: 'error',
        })
        return
    }

    if (!isOnline.value) {
        ElMessage({
            message: '离线模式,不能登录会员',
            type: 'error',
        })
        return
    }
    isShowPhoneKeyboard.value = true
}

//判断优惠券是否在有效期内
function isCouponInUsingTime(coupon) {

    //判断生效时段
    let { startUseTime, endUseTime, startUsePeriodTime, endUsePeriodTime } = coupon

    let today = getDateTimeString(new Date(currentTime.value)); //获取年月日
    startUsePeriodTime = startUsePeriodTime ? new Date(today + ' ' + startUsePeriodTime) : null
    endUsePeriodTime = endUsePeriodTime ? new Date(today + ' ' + endUsePeriodTime) : null


    if (new Date(currentTime.value) >= new Date(startUseTime) && new Date(currentTime.value) <= new Date(endUseTime)) {
        if (startUsePeriodTime && endUsePeriodTime) {
            if (new Date(currentTime.value) >= startUsePeriodTime && new Date(currentTime.value) <= endUsePeriodTime) {
                //console.log('在生效时段内~')
                return true
            } else {
                //console.log('不在生效时段内~')
                return false
            }
        } else {
            //console.log('在生效时段内~')
            return true
        }

    } else {
        //console.log('不在生效时段内~')
        return false
    }

}

//计算可用优惠券和不可用优惠券 
function calculateUsableCouponAndUnusableCoupon() {
    //找出购物车所有商品（除了赠品）
    let curShoppingCarData = shoppingCarData.value[currentActiveVariableIndex.value].filter(item => !item.isGift)
    //console.log(curShoppingCarData)
    //找出当前所有满足的活动以及商品 如果活动与优惠券共享则保留商品，如果不共享则排除该商品
    //不共享的商品id 数组
    const unsharedGoodsIDs = currentActivityDiscountData.value.filter(item => item.activity.isUseCoupon === '1').map(item => item.goods.map(childItem => childItem.goodsID)).flat()
    curShoppingCarData = curShoppingCarData.filter(item => !unsharedGoodsIDs.includes(item.goodsID))
    // console.log(curShoppingCarData.value)
    //剩余购物车商品 所有可用的优惠券

    const currentShoppingCarUsableCouponIDs = [...new Set(curShoppingCarData.map(item => item.couponIDs).flat())]

    currentUsableCouponData.value = []
    currentUnusableCouponData.value = []
    // console.log(currentCouponList.value)
    for (let i = 0; i < currentCouponList.value.length; i++) {
        // console.log(couponsForShop.value.findIndex(item => item.couponID === currentCouponList.value[i].couponID) != -1)
        // console.log(currentShoppingCarUsableCouponIDs.includes(currentCouponList.value[i].couponID))
        // console.log(isCouponInUsingTime(currentCouponList.value[i]))
        // console.log('---------')
        // 门店可用、商品可用、在生效时间内
        if (couponsForShop.value.findIndex(item => item.couponID === currentCouponList.value[i].couponID) != -1 && currentShoppingCarUsableCouponIDs.includes(currentCouponList.value[i].couponID) && isCouponInUsingTime(currentCouponList.value[i])) {
            // console.log(currentCouponList.value[i])
            currentUsableCouponData.value.push(currentCouponList.value[i])
        } else {
            currentUnusableCouponData.value.push(currentCouponList.value[i])
        }
    }

    //console.log(currentUsableCouponData.value)


    //查找可用优惠券的适用商品 (把可用商品的集合 加到优惠券上（后面计算优惠金额应该分到哪些品上 用）)
    for (let i = 0; i < currentUsableCouponData.value.length; i++) {
        //判断是否 仅原价商品使用
        if (currentUsableCouponData.value[i].originalPrice === '1') { //仅原价商品可使用
            // 这里还需要判断是否会员价
            // if(!currentMemberInfo.value){

            // }
            // console.log(curShoppingCarData)
            currentUsableCouponData.value[i]['usableGoods'] = curShoppingCarData.filter(item => item.basicPrice === item.retailPrice && item.couponIDs.includes(currentUsableCouponData.value[i].couponID))
        } else {
            currentUsableCouponData.value[i]['usableGoods'] = curShoppingCarData.filter(item => item.couponIDs.includes(currentUsableCouponData.value[i].couponID))
        }

    }



    //如果某个优惠券的可用商品长度为0 ，则把它删除 并添加到不可用优惠券中
    for (let i = 0; i < currentUsableCouponData.value.length; i++) {
        if (currentUsableCouponData.value[i]['usableGoods'].length <= 0) {
            //  console.log(currentUsableCouponData.value[i])
            currentUsableCouponData.value.splice(i, 1)
            currentUnusableCouponData.value.push(currentUsableCouponData.value[i])
            i--

        }
    }

    //如果某个优惠券的rule 不满足，则把它删除 并添加到不可用优惠券中
    for (let i = 0; i < currentUsableCouponData.value.length; i++) {
        let totalPrice = currentUsableCouponData.value[i]['usableGoods'].reduce((prev, currentVal) => {
            return NP.plus(prev, roundNumber(currentVal.retailPrice, currentVal.quantity))
        }, 0)

        if (totalPrice < currentUsableCouponData.value[i].rule) {

            currentUsableCouponData.value.splice(i, 1)
            currentUnusableCouponData.value.push(currentUsableCouponData.value[i])
            i--

        }
    }





    // console.log(currentUsableCouponData.value)
    // //console.log(shoppingCarData.value[currentActiveVariableIndex.value])


    //如果当前选择了优惠券，但是重新计算后可用优惠券不包含当前优惠券时，需要删除当前优惠券，并且删除优惠信息里的优惠记录和优惠券抵扣金额
    if (currentUsingCoupon.value) {
        const found = currentUsableCouponData.value.find(item => item.memberCouponID === currentUsingCoupon.value.memberCouponID)
        if (!found) {
            currentUsingCoupon.value = null
            currentCouponDiscountPrice.value = 0
            currentActivityDiscountData.value = currentActivityDiscountData.value.filter(item => !item.isCoupon)
        }
    }
}
watch(() => currentUsingCoupon.value, () => {
    console.log('选择的优惠券变化了~')
    calculateCouponDiscountPrice()
}, { immediate: true, deep: true })

//计算已选优惠券的优惠金额
function calculateCouponDiscountPrice() {


    //console.log(currentUsingCoupon.value)
    if (currentUsingCoupon.value) { //当前使用了优惠券
        const { type, rule, reduction } = currentUsingCoupon.value
        //计算总优惠金额(订单总金额 - 活动优惠 如果小于优惠券减少的金额，则实际优惠券抵扣金额 = 订单总金额 - 活动优惠)
        let leavePrice = NP.minus(orderTotalPrice.value, currentTotalActivityDiscount.value)

        if (type === '1') { //满减券
            const groupGoods = currentUsingCoupon.value.usableGoods
            //计算商品总金额
            let totalPrice = calculateActivityGroupTotalPrice(groupGoods)
            let totalDiscountPrice = reduction
            totalDiscountPrice = leavePrice < reduction ? leavePrice : reduction
            currentCouponDiscountPrice.value = totalDiscountPrice
            //计算 除最后一个商品的 活动优惠金额总合 
            let totalActiveDiscountExcludeLast = calculateTotalActiveDiscountExcludeLast(groupGoods, totalPrice, totalDiscountPrice)
            //计算每个品的 活动优惠 
            let mapGoods = calculateEveryGoodsDiscount(groupGoods, totalPrice, totalDiscountPrice, totalActiveDiscountExcludeLast)


            //计算优惠券对应的每个商品的优惠 （如果没有优惠券记录则添加 否则是修改  根据isCoupon 来判断）
            const index = currentActivityDiscountData.value.findIndex(item => item.isCoupon)
            //console.log(index)
            if (index == -1) {
                addActivityDiscountLog({ isCoupon: true, activity: null, goods: mapGoods, type: '优惠券抵扣', text: `无门槛 减${reduction}`, discountPrice: totalDiscountPrice })
            } else {
                currentActivityDiscountData.value.splice(index, 1, { isCoupon: true, activity: null, goods: mapGoods, type: '优惠券抵扣', text: `无门槛 减${reduction}`, discountPrice: totalDiscountPrice })
            }




        } else if (type === '2') { //打折券
            const groupGoods = currentUsingCoupon.value.usableGoods
            //计算商品总金额
            let totalPrice = calculateActivityGroupTotalPrice(groupGoods)
            //计算优惠券优惠金额
            let reduceDiscount = NP.minus(10, reduction)
            let totalDiscountPrice = roundNumber(NP.times(totalPrice, NP.divide(reduceDiscount, 10)))
            totalDiscountPrice = leavePrice < totalDiscountPrice ? leavePrice : totalDiscountPrice


            //计算 除最后一个商品的 活动优惠金额总合 
            let totalActiveDiscountExcludeLast = calculateTotalActiveDiscountExcludeLast(groupGoods, totalPrice, totalDiscountPrice)
            //计算每个品的 活动优惠 
            let mapGoods = calculateEveryGoodsDiscount(groupGoods, totalPrice, totalDiscountPrice, totalActiveDiscountExcludeLast)

            currentCouponDiscountPrice.value = totalDiscountPrice

            //计算优惠券对应的每个商品的优惠 （如果没有优惠券记录则添加 否则是修改  根据isCoupon 来判断）
            const index = currentActivityDiscountData.value.findIndex(item => item.isCoupon)
            //console.log(index)
            if (index == -1) {
                addActivityDiscountLog({ isCoupon: true, activity: null, goods: mapGoods, type: '优惠券抵扣', text: `无门槛 打${reduction}折`, discountPrice: totalDiscountPrice })
            } else {
                currentActivityDiscountData.value.splice(index, 1, { isCoupon: true, activity: null, goods: mapGoods, type: '优惠券抵扣', text: `无门槛 打${reduction}折`, discountPrice: totalDiscountPrice })
            }




        } else if (type === '3') { //兑换券   
            //  console.log('兑换券！')
            const groupGoods = currentUsingCoupon.value.usableGoods

            let mapGoods = groupGoods.map(item => ({ ...item, activityDiscount: item.retailPrice })) //这里兑换券默认数量为1
            //计算兑换券优惠总金额
            let totalDiscountPrice = groupGoods.reduce((prev, currentVal) => {
                return NP.plus(prev, currentVal.retailPrice)
            }, 0)
            totalDiscountPrice = leavePrice < totalDiscountPrice ? leavePrice : totalDiscountPrice
            currentCouponDiscountPrice.value = totalDiscountPrice
            //计算优惠券对应的每个商品的优惠 （如果没有优惠券记录则添加 否则是修改  根据isCoupon 来判断）
            const index = currentActivityDiscountData.value.findIndex(item => item.isCoupon)
            //console.log(index)
            if (index == -1) {
                addActivityDiscountLog({ isCoupon: true, activity: null, goods: mapGoods, type: '优惠券抵扣', text: `兑换券`, discountPrice: totalDiscountPrice })
            } else {
                currentActivityDiscountData.value.splice(index, 1, { isCoupon: true, activity: null, goods: mapGoods, type: '优惠券抵扣', text: `兑换券`, discountPrice: totalDiscountPrice })
            }



        }

    } else {
        console.log(currentActivityDiscountData.value)
        const index = currentActivityDiscountData.value.findIndex(item => item.isCoupon)
        console.log('~~~~~~', index)
        if (index !== -1) { //清空优惠券的优惠明细
            currentActivityDiscountData.value.splice(index, 1)
        }
    }


}


//四舍五入(保留2位小数)
function roundNumber(number) {
    return NP.round(number, 2)
}


//打开赠品弹窗
function openGiftDialog() {
    giftDialogVisible.value = true
}

//打开活动优惠明细弹窗
function openActivityDiscountDialog() {
    activityDiscountDialogVisible.value = true
}


const priceSchemesID = computed(() => allData.value.priceSchemesID) //价格方案ID
//console.log('priceSchemesID', priceSchemesID.value)
const currentSelectGoods = ref({}) //当前选中商品
// const shoppingCarData = ref([[], [], [], []]) //购物车数据
const currentShoppingCarPageNo = ref(1) //当前购物车页数
const currentRow = ref()
const shoppingCarTableRef = ref()
const shoppingCarPageSize = ref(4) //每页条数
//当前选择的结算栏 V1 、V2 ... 索引
// const currentActiveVariableIndex = ref(0)
const delRowDialogVisible = ref(false) //删除行 弹窗
const clearDialogVisible = ref(false) //清空 弹窗

const isShowPayKeyboard = ref(false)
const currentPayType = ref(null)
const isPayInputSelect = ref(false)

//活动优惠
const totalActivityDiscount = ref([0, 0, 0, 0])
//当前活动优惠
const currentTotalActivityDiscount = computed({
    get() {
        return totalActivityDiscount.value[currentActiveVariableIndex.value]
    },
    set(newVal) {
        totalActivityDiscount.value[currentActiveVariableIndex.value] = newVal
    }
})

const layout = [
    '1 2 3',
    '4 5 6',
    '7 8 9',
    '. 0 {bksp}']
const payLayout = ref(layout.map((item, index) => item + ' ' + quickPayList.value[index]))
// payLayout.value.forEach((item,index)=>{
//     //console.log(item,quickPayList.value[index])
//     item = item+' '+quickPayList.value[index]
// })    

//打开优惠券弹窗
function openCouponDialog() {
    //打开弹窗前重置可用优惠券和不可用优惠券的当前页
    currentUsableCouponPageNo.value = 1
    currentUnusableCouponPageNo.value = 1
    couponDialogVisible.value = true
}

//选择优惠券
function chooseCoupon(item) {
    //console.log(item)
    if (!currentSelectCoupon.value) {
        currentSelectCoupon.value = item
    } else {
        currentSelectCoupon.value = null
    }
}
//清除券
function clearCoupon() {
    currentSelectCoupon.value = null
    currentUsingCoupon.value = null
    couponDialogVisible.value = false
    currentCouponDiscountPrice.value = 0
}

watch(() => couponDialogVisible.value, (newVal) => {
    if (newVal) {
        currentSelectCoupon.value = currentUsingCoupon.value
    }
})

//确认选择优惠券
function confrimSelectCoupon() {
    currentUsingCoupon.value = currentSelectCoupon.value
    couponDialogVisible.value = false

}


watch(() => currentPriceType.value, (newVal) => {
    if (newVal === 'RP') {
        document.documentElement.style.setProperty('--el-color-primary', '#409EFF');
    } else {
        document.documentElement.style.setProperty('--el-color-primary', '#E6A23C');
    }
})

// onActivated(() => {
//     //console.log('Component activated');
//     //激活状态读称，销毁就关闭定时器
//     window.electron.ipcRenderer.send('read-weight')
// })
// onDeactivated(() => {
//     //console.log('Component deactivated~')
//     //激活状态读称，销毁就关闭定时器
//     window.electron.ipcRenderer.send('close-read-weight')
// })

onMounted(() => {
    //console.log('mounted~')


    //console.log(shoppingCarTableRef.value)
    //计算左侧购物车分页条数
    let tableHeight = shoppingCarTableRef.value.offsetHeight
    let singleRowHeight = 64 //每行高度
    shoppingCarPageSize.value = Math.floor((tableHeight - 40) / singleRowHeight) //减去header 的高度
    //console.log(shoppingCarPageSize.value)
    
})

onActivated(() => {
    window.addEventListener('keydown', handleKeyDown);
})
onDeactivated(() => {
    window.removeEventListener('keydown', handleKeyDown);
})
// onBeforeUnmount(() => {
//     window.removeEventListener('keydown', handleKeyDown);
// })
//语音播报
function speak(text) {
    try {
        let msg = new SpeechSynthesisUtterance();
        msg.text = text;
        // 可选：设置语速、音调等参数
        msg.lang = 'zh-CN'; // 设置语言为中文
        msg.rate = 1.2; // 语速
        msg.pitch = 2; // 音调
        msg.volume = 20; // 音量

        // 开始语音播报
        window.speechSynthesis.speak(msg);
    } catch (error) {
        console.log(error)
    }

}


//订单查询跳转
function toOrderQuery() {

    router.push({ name: 'orderquery' })
}


const currentPriceTypeGoodsData = computed(() => { //当前价格类型商品数据
    if (!allGoodsData.value) {
        return []
    } else {
        return allGoodsData.value.find(item => item.priceType === currentPriceType.value)?.posSalePanelGoodsVos || []
    }

})


const currentActiveGroupName = ref('全部') //当前选中分组名
function changeGroup(item, index) { //切换分组
    currentPageNo.value = 1
    currentActiveGroupName.value = item
}



const currentPageNo = ref(1) //当前页
const totalPages = computed(() => {
    const index = currentPriceTypeGoodsData.value.findIndex(item => item.panelType == currentActiveGroupName.value)
    return Math.ceil((currentPriceTypeGoodsData.value[index].posSaleGoodsPriceVos
        .filter(item => {
            const pinyinItem = pinyin(item.goodsName, {
                style: pinyin.STYLE_FIRST_LETTER //首字母模式
            }).join('')
            return pinyinItem.indexOf(goodsSearchKeywords.value) != -1
        }).length - (pageSize.value - 1)) / (pageSize.value - 2)) + 1;
})

watch(() => goodsSearchKeywords.value, (_) => {
    currentPageNo.value = 1


})
//当前页右侧商品数据
const currentPageData = computed(() => {

    // //console.log(goodsSearchKeywords.value)
    const activeGroupIndex = currentPriceTypeGoodsData.value.findIndex(item => item.panelType === currentActiveGroupName.value)
    let items = (currentPriceTypeGoodsData.value[activeGroupIndex]?.posSaleGoodsPriceVos || [])
        .filter(item => {
            const pinyinItem = pinyin(item.goodsName, {
                style: pinyin.STYLE_FIRST_LETTER //首字母模式
            }).join('')
            ////console.log(pinyinItem)
            return pinyinItem.indexOf(goodsSearchKeywords.value) != -1
        })
    // //console.log(items)
    const itemsPerPageFirstPage = pageSize.value - 1
    const itemsPerPageOtherPages = pageSize.value - 2

    let start, end;
    if (currentPageNo.value === 1) {
        start = 0;
        end = itemsPerPageFirstPage;
    } else if (currentPageNo.value === totalPages.value) {
        start = itemsPerPageFirstPage + (totalPages.value - 2) * itemsPerPageOtherPages;
        end = items.length;
    } else {
        start = itemsPerPageFirstPage + (currentPageNo.value - 2) * itemsPerPageOtherPages;
        end = start + itemsPerPageOtherPages;

    }

    // 分割商品列表
    const paginatedItems = items.slice(start, end);
    return paginatedItems
})


// const setCurrent = (row) => {
//     shoppingCarTableRef.value!.setCurrentRow(row)
// }
const handleCurrentChange = (val) => {
    currentRow.value = val
}


//加
function handleMyInputPlus(row) {
    row.quantity++

}
//减
function handleMyInputMinus(row) {
    if (row.quantity == 1) {
        currentRow.value = row
        delRowDialogVisible.value = true

    } else {
        row.quantity--
    }

}
//输入
function handleMyInputCount(row) {

    if (row.isGift) { //赠品不允许修改数量
        return false
    }
    const { isQuantityUnit } = row
    if (isQuantityUnit === 'y') {//数量单位
        isShowPoint.value = false
    } else {
        isShowPoint.value = true
    }
    currentRow.value = row
    isShowCountKeyboard.value = true
}
//确定数量或重量
function onConfirmCountOrWeight(val) {

    currentRow.value.quantity = val
    isShowCountKeyboard.value = false

}

//会员消费
const memberFee = computed(() => {
    let totalFee = 0
    if (payTicketInfo.value && payTicketInfo.value.reqData) {
        const found = payTicketInfo.value.reqData?.orderPayDto.orderPayAddDtos.find(item => item.payType == 'MB')
        if (found) {
            return NP.plus(totalFee, found.payAmount, found.giveCash)
        }

    }
    return totalFee

})



function showSearchKeyboard() {
    //console.log('focus!')
    goodsSearchKeywords.value = ''
    isShowSearchKeyboard.value = true
    //console.log(isShowSearchKeyboard)
}

function onSearchKeyboardChange(val) {
    //console.log('val:' + val)
    goodsSearchKeywords.value = val
}
function onPhoneKeyboardChange(val) {
    //console.log(val)
    // goodsSearchKeywords.value = val
}
function confirmPhone(val) {
    currentTelPhone.value = val
    loginMember(val)
}

//退出会员
function logoutMember() {
    currentMemberInfo.value = null
    currentTelPhone.value = ''

    //清除当前已选优惠券
    currentUsingCoupon.value = null
    //重新计算优惠
    //计算活动优惠
    calculateActivityDiscount()


    //计算可用优惠券
    calculateUsableCouponAndUnusableCoupon()
    //计算优惠券明细
    calculateCouponDiscountPrice()
    currentMemberIsLogin.value = false
    //清空已选优惠券
    currentSelectCoupon.value = null
    //清除当前使用优惠券
    currentUsingCoupon.value = null
    //清除优惠券抵扣金额
    currentCouponDiscountPrice.value = 0
}

//获取会员优惠券信息
async function getCoupon() {

    const memberID = currentMemberInfo.value?.id || ''
    try {
        const { data } = await getMemberCoupon(saleOrganizationID, shopID, memberID)
        currentCouponList.value = data
        //console.log(data)
        //计算可用优惠券
        calculateUsableCouponAndUnusableCoupon()
    } catch (error) {
        console.log(error)
    }

}


//会员登录 
async function loginMember(phoneNumber: string = '', memberID: string = '') {
    try {
        const { data } = await memberLogin({ saleOrganizationID, phoneNumber, memberID })
        currentMemberInfo.value = data

        if (data == null) { //未注册 显示注册弹窗
            registerMemeberDialogVisible.value = true
        } else {
            //查询优惠券信息
            await getCoupon()
            //登录后重新计算优惠信息
            //计算活动优惠
            calculateActivityDiscount()
            //计算可用优惠券
            calculateUsableCouponAndUnusableCoupon()
            //计算优惠明细
            calculateCouponDiscountPrice()

            //多设置一个标识 会员登录
            currentMemberIsLogin.value = true

        }
        //console.log(data)
    } catch (error) {
        console.log(error)
    } finally {

    }

}


//读取扫码枪信息
let barcodeBuffer = '';
let timeoutId;
let isProcessing = false


const handleKeyDown = (event) => {
    // 阻止默认行为，避免按钮聚焦
    event.preventDefault();
    // console.log('---------')
    // console.log(event)
    // 忽略修饰键
    if (event.key.length > 1 && event.key !== 'Enter') return;

    // 如果当前按键是回车键（扫码枪通常以回车键结束）
    if (event.key === 'Enter') { //如果是Enter表示扫码完成
        authCode.value = ''

        handleBarCode(barcodeBuffer.trim())

        barcodeBuffer = '';
        return
    } else {
        barcodeBuffer += event.key;
    }

}




const handleBarCode = debounce(function (barcodeBuffer) {
    //console.log(barcodeBuffer)


    if (currentPayType.value) { //支付扫码
        // console.log(isShowElectronicDialog.value)
        // console.log(isShowElectronicDialog.value)
        // console.log(isShowElectronicDialog.value == true)
        if (currentPayType.value.pkey === 'EP' && isShowElectronicDialog.value == true) { //电子支付
            // console.log('电子支付')
            // console.log(barcodeBuffer)
            authCode.value = barcodeBuffer

            //console.log('电子支付~~')
            toCreateOrder('EP') //电子支付

        } else if (currentPayType.value.pkey === 'MB' && isShowElectronicDialog.value == true) { //会员支付
            //  console.log('会员支付')
            // authCode.value = barcodeBuffer
            let memerID = currentMemberInfo.value?.id || ''

            getMemberInfoByCode(saleOrganizationID, barcodeBuffer, memerID).then(res => {
                isShowElectronicDialog.value = false

                let resultMemberID = res.data.memberID
                // if(memerID==resultMemberID){
                //     ElMessage({
                //         message:'每个订单只能使用一次会员支付',
                //         type:'error'
                //     })
                //     return false
                // }
                //如果当前会员已登录，则必须扫当前会员的付款码
                if (currentMemberInfo.value && currentMemberIsLogin.value) {
                    if (memerID != resultMemberID) {
                        ElMessage({
                            message: '非当前会员的付款码,不可使用',
                            type: 'error'
                        })
                        return false
                    }

                }


                currentMemberInfo.value = res.data && { ...res.data, id: resultMemberID }
                //计算活动优惠
                calculateActivityDiscount()

                //计算优惠券优惠明细
                calculateCouponDiscountPrice()





                //重新计算后 如果应付金额小于0（用户已经付了部分钱，扫码后发现有会员专享，实际需要支付金额小于等于已付金额，需要提示找零 并直接创建订单）
                if (computedUnreceivePrice.value <= 0) {
                   // console.log('重新计算后，应付金额小于等于0')
                    if (computedUnreceivePrice.value < 0) {
                        let msg = '当前有会员价商品,应付金额发生变动请确认，需找零' + Math.abs(computedUnreceivePrice.value)
                        ElMessageBox.alert(msg, '提示', {
                            showClose:false,
                            confirmButtonText: '确认',
                            callback: (action: Action) => {
                                //此时需要修改支付方式的金额
                               
                                if(payTypeTable.value&&payTypeTable.value[0]&&payTypeTable.value[0].payAmount){
                                    payTypeTable.value[0].payAmount = NP.minus(payTypeTable.value[0].payAmount,Math.abs(computedUnreceivePrice.value))
                                }
                                
                                toCreateOrder()
                            },
                        })
                        
                    }else{
                        toCreateOrder()
                    }
                    

                } else {
                    //如果会员余额足够支付 （本金 + 赠金 > 未付金额）
                    const payType = payTypeList.value.find(item => item.pkey === 'MB')
                    if (payType) {
                        // console.log(payType)

                        if (NP.plus(currentMemberInfo.value.giveCash, currentMemberInfo.value.capital) >= computedUnreceivePrice.value) {//余额足够支付
                            if (currentMemberInfo.value.giveCash >= computedUnreceivePrice.value) { //赠金足够支付
                                payTypeTable.value.unshift({ ...payType, giveCash: computedUnreceivePrice.value, payAmount: 0 })

                                //  console.log(payTypeTable.value[0])
                            } else {
                                payTypeTable.value.unshift({ ...payType, giveCash: currentMemberInfo.value.giveCash, payAmount: NP.minus(computedUnreceivePrice.value, currentMemberInfo.value.giveCash) })
                            }
                            isShowElectronicDialog.value = false
                            //console.log('创建会员支付订单！')
                            toCreateOrder()
                        } else {//会员余额不足
                            //这里是同步的会导致重复执行（临时增加判断）
                            const index = payTypeTable.value.findIndex(item => item.pkey === 'MB')
                            //  console.log(index)
                            if (index == -1) {
                                payTypeTable.value.unshift({ ...payType, giveCash: currentMemberInfo.value.giveCash, payAmount: currentMemberInfo.value.capital })

                                // console.log('会员余额不足！')
                            } else {
                                payTypeTable.value[index] = { ...payType, giveCash: currentMemberInfo.value.giveCash, payAmount: currentMemberInfo.value.capital }
                            }
                            isShowElectronicDialog.value = false

                        }

                    }

                }









            }).catch(error => {
                // console.log(111)
                // console.log(error == null)
                console.log(error)
            }).finally(() => {
                //console.log('finnaly!')

            })

            // 
        } else if (currentPayType.value.pkey === SHOPPINGCARDKEY) {//购物卡

            scanShoppingCard(barcodeBuffer)
        }
    } else if (electronicRechargeDialogVisible.value) { //会员充值 电子支付扫码
        rechargeAuthCode.value = barcodeBuffer
        toRecharge()

    } else {
        //console.log(barcodeBuffer)
        if (barcodeBuffer.startsWith('M')) { //19位会员码
            //console.log('Received barcode:', barcodeBuffer);
            // 处理接收到的条形码数据
            //console.log(barcodeBuffer.substring(1))
            loginMember('', barcodeBuffer.substring(1))
        } else { //商品码
            //console.log('商品码~')
            const allGoods = currentPriceTypeGoodsData.value[0]?.posSaleGoodsPriceVos || []
            const foundGoods = allGoods.find(item => item.goodsBarCode.split(',').findIndex(childItem => childItem === barcodeBuffer) != -1)

            if (foundGoods) { //如果找到了则默认数量为1
                // console.log(foundGoods)
                selectGoods(foundGoods)
            } else {//如果没找到 则判断是否是生鲜码
                const code = barcodeBuffer.substring(2, 7) //取中间5位
                const freshFood = allGoods.find(item => item.goodsBarCode === code)
                if (freshFood) {
                    freshFood.quantity = NP.divide(barcodeBuffer.substring(8, 12) * 1, 1000) //重量取5位 ，单位是g
                    shoppingCarData.value[currentActiveVariableIndex.value].unshift({ ...freshFood, currentTime: currentTime.value })

                } else {
                    ElMessage({
                        message: '该条码无效！',
                        type: 'error'
                    })
                    // console.log('该条码无效！')

                }
            }
        }
    }


}, 300)


//取消注册会员
function cancelRegisterMemeber() {
    registerMemeberDialogVisible.value = false
    logoutMember()
}
//确认注册会员
async function confirmRegisterMemeber() {
    const saleOrganizationName = shopInfo.value.organizationName

    const phoneNumber = currentTelPhone.value
    const userID = userInfo.value.user_userId
    const userName = userInfo.value.user_name


    try {
        const { data } = await memberRegister({ saleOrganizationID, saleOrganizationName, shopID, shopName, phoneNumber, userID, userName })
        await loginMember(phoneNumber)
        registerMemeberDialogVisible.value = false
    } catch (error) {
        console.log(error)
    }


}

//选择充值活动
function onSelectActiity(item, index) {
    if (index === currentRechargeActivityIndex.value) {
        currentRechargeActivityIndex.value = '' //已选 取消
    } else {
        currentRechargeActivityIndex.value = index
    }

}
//打开充值弹窗
async function openRechargeDialog() {
    try {
        const { data } = await getRechargeActivity(shopID)
        rechargeActivityList.value = data
        rechargeDialogVisible.value = true
    } catch (error) {
        console.log(error)
    }

}


//现金充值 、电子支付充值
async function toRecharge() {
    const activityItem = rechargeActivityList.value[currentRechargeActivityIndex.value]
    const saleOrganizationName = shopInfo.value.organizationName
    const userID = userInfo.value.user_userId
    const userName = userInfo.value.user_name
    const balanceRecordCouponAddDtos = activityItem
    const reqData = {
        authCode: rechargeAuthCode.value,
        memberID: currentMemberInfo.value.id,
        memberPhoneNumber: currentMemberInfo.value.phoneNumber,
        capital: activityItem.capital,
        giveCash: activityItem.giveCash,
        receivableAmount: activityItem.capital,
        saleOrganizationID,
        saleOrganizationName,
        shopCode: shopInfo.value.shopCode,
        shopID,
        shopName,
        basicActivityID: activityItem.basicActivityID,
        basicActivityName: activityItem.basicActivityName,
        memberRechargeConfigID: activityItem.memberRechargeConfigID,
        balanceRecordCouponAddDtos: activityItem.activityMemberRechargeCouponVos.map(item => ({ ...item, couponText: item.discountText }))
    }


    try {
        const { data, msg } = await cashRecharge(reqData)
        ElMessage({
            message: msg,
            type: 'success',
        })



        //小票需要的数据
        rechargeTicketInfo.value = {
            orderNo: data.orderNO,
            reqData,
            payType: rechargeAuthCode.value ? '电子支付' : '现金支付'
        }

        currentMemberInfo.value.capital = NP.plus(currentMemberInfo.value.capital, activityItem.capital, activityItem.giveCash)
        if (electronicRechargeDialogVisible.value) {
            electronicRechargeDialogVisible.value = false
        }
        if (cashRechargeDialogVisible.value) {
            cashRechargeDialogVisible.value = false
        }
        //清空活动选中索引
        currentRechargeActivityIndex.value = ''

        if (rechargeAuthCode.value) { //清空付款码
            rechargeAuthCode.value = ''
        }

        //打印小票
        printTicket({ type: 'recharge', orderNum: data.orderNO })

        //充值成功后重新获取优惠券信息
        await getCoupon()
        // rechargeDialogVisible.value = false
    } catch (error) {
        console.log(error)
    } finally {

    }

}

//确认现金充值
async function confirmCashRecharge() {
    rechargeAuthCode.value = ''
    await toRecharge()

}

//现金、电子支付
function confirmRecharge(type) {
    if (currentRechargeActivityIndex.value === '') { //未选择活动不能提交
        ElMessage({
            message: '请选择充值活动',
            type: 'warning',
        })
        return false
    }
    if (type == 0) { //现金支付
        cashRechargeDialogVisible.value = true


    } else if (type == 1) {//电子支付
        electronicRechargeDialogVisible.value = true
    }
}

//判断活动是否在生效时间内 (活动id，活动集合，当前时间)
function isActiveInUsableTime(activityId, activitysArr, currentTime) {
    const foundActivity = activitysArr.find(item => item.activityID === activityId)
    if (foundActivity) {
        // console.log(foundActivity)
        //判断生效时段
        let { startUseTime, endUseTime, startUsePeriodTime, endUsePeriodTime } = foundActivity
        let today = getDateTimeString(new Date(currentTime)); //获取年月日
        startUsePeriodTime = startUsePeriodTime ? new Date(today + ' ' + startUsePeriodTime) : null
        endUsePeriodTime = endUsePeriodTime ? new Date(today + ' ' + endUsePeriodTime) : null
        let nowTime = currentTime
        // //console.log(getTimeString(new Date(nowTime)))
        // //console.log(getTimeString(new Date(startUseTime)))
        // //console.log(getTimeString(new Date(new Date(endUseTime))))
        // //console.log(getTimeString(new Date(startUsePeriodTime)))
        // //console.log(getTimeString(new Date(endUsePeriodTime)))
        if (new Date(nowTime) >= new Date(startUseTime) && new Date(nowTime) <= new Date(endUseTime)) {
            if (startUsePeriodTime && endUsePeriodTime) {
                if (new Date(nowTime) >= startUsePeriodTime && new Date(nowTime) <= endUsePeriodTime) {
                    console.log('在生效时段内~')
                    return true
                } else {
                    console.log('不在生效时段内~')
                    return false
                }
            } else {
                console.log('在生效时段内~')
                return true

            }

        } else {
            console.log('不在生效时段内~')
            return false
        }
    }

    return false
}

//选择商品
function selectGoods(goods) {
    //console.log(goods)
    currentSelectGoods.value = goods
    const { isQuantityUnit } = goods

    if (isQuantityUnit === 'y') { //数量单位
        const foundIndex = shoppingCarData.value[currentActiveVariableIndex.value].findIndex(item => item.goodsID === goods.goodsID && !item.isGift) //排除赠品
        if (foundIndex == -1) {
            //判断价格类型商品是否在生效时间内，如果不在生效时间内 则设置retailPrice的值为basicPrice
            if (goods.retailPrice < goods.basicPrice && !isActiveInUsableTime(goods.priceActivityID, priceActivitys.value, currentTime.value)) {

                shoppingCarData.value[currentActiveVariableIndex.value].unshift({ ...goods, retailPrice: goods.basicPrice, quantity: 1, currentTime: currentTime.value })
            } else {
                shoppingCarData.value[currentActiveVariableIndex.value].unshift({ ...goods, quantity: 1, currentTime: currentTime.value })
            }



        } else {
            const found = shoppingCarData.value[currentActiveVariableIndex.value][foundIndex]
            // console.log(found)

            found.quantity = NP.plus(found.quantity, 1)

            //如果找到的商品不在当前页 ，则把它删除，然后添加到首位后重新分页
            if (!currentTableData.value.find(item => item.goodsID === goods.goodsID)) {
                shoppingCarData.value[currentActiveVariableIndex.value].splice(foundIndex, 1)
                shoppingCarData.value[currentActiveVariableIndex.value].unshift({ ...goods, quantity: found.quantity, currentTime: currentTime.value })
            }
        }

    } else {
        //重量单位 打开弹窗
        isShowSelectGoodsDialog.value = true

    }

    //console.log(shoppingCarData.value)
}

//确认选择重量商品
function confirmSelectGoods() {
     if (weight.value !== '0.000' && weight.value) {
    //临时不考虑称上是否有重量 (这里的quantity 如果有就取它的值，这是生鲜码扫码后赋值到这个属性上)

    shoppingCarData.value[currentActiveVariableIndex.value].unshift({ ...toRefs(currentSelectGoods.value), quantity: weight.value, currentTime: currentTime.value })
    isShowSelectGoodsDialog.value = false
     } else {
        ElMessage({
           type: 'error',
            message: '当前重量不正确',
         })
     }



}



//当前页购物车数据
const currentTableData = computed(() => {
    // //console.log(paginateData(shoppingCarData.value[currentActiveVariableIndex.value],shoppingCarPageSize.value))
    return paginateData(shoppingCarData.value[currentActiveVariableIndex.value], shoppingCarPageSize.value)[currentShoppingCarPageNo.value - 1] || []

})
//console.log(paginateData(shoppingCarData.value[currentActiveVariableIndex.value], shoppingCarPageSize.value))
//console.log(currentShoppingCarPageNo.value - 1)
//计算序号
function indexMethod(index) {
    //console.log(index)
    return shoppingCarData.value[currentActiveVariableIndex.value].length - (currentShoppingCarPageNo.value - 1) * shoppingCarPageSize.value - index
}



function prevCar() {
    if (currentShoppingCarPageNo.value <= 1) return
    currentShoppingCarPageNo.value--
}
function nextCar() {
    if (currentShoppingCarPageNo.value >= currentTableData.value.length) return
    currentShoppingCarPageNo.value++
}

//切换v1、v2 ...
function changeVariable(index) {

    userStore.setCurrentActiveVariableIndex(index)
    //重置当前页为1
    currentShoppingCarPageNo.value = 1
    calculateActivityDiscount() //重新计算活动优惠
}

//每一个Variable 的总件数 重量单位的每行记作1 数量单位的求quantity
const computedVariableNums = computed(() => {
    return (index) => {
        let total = 0
        for (let i = 0; i < shoppingCarData.value[index].length; i++) {
            if (shoppingCarData.value[index][i].isQuantityUnit === 'y') {
                total += shoppingCarData.value[index][i].quantity * 1
            } else {
                total += 1
            }
        }
        return total

    }

})


//删除行
function delRow() {
    delRowDialogVisible.value = true
}
function confirmDelRow() {
    const isQuantityUnit = currentRow.value.isQuantityUnit


    if (isQuantityUnit === 'y') { //数量单位
        const index = shoppingCarData.value[currentActiveVariableIndex.value].findIndex(item => item.goodsID === currentRow.value.goodsID)
        shoppingCarData.value[currentActiveVariableIndex.value].splice(index, 1)
    } else { //重量单位还需要判断 currentTime 来确定唯一值
        const index = shoppingCarData.value[currentActiveVariableIndex.value].findIndex(item => item.goodsID === currentRow.value.goodsID && item.currentTime === currentRow.value.currentTime)
        shoppingCarData.value[currentActiveVariableIndex.value].splice(index, 1)
    }

    // //删除某个品时，需要判断删除该品后是否还满足赠品活动了，如果不满足则应该删除赠品
    //console.log(currentGoodsGiftAndActivitys.value)
    nextTick(() => {
        //console.log(currentGoodsGiftAndActivitys.value)
        if (currentGoodsGiftAndActivitys.value.length > 0) {
            //查找所有赠品
            const gifts = shoppingCarData.value[currentActiveVariableIndex.value].filter(item => item.isGift)
            const currentActivityIDs = currentGoodsGiftAndActivitys.value.map(item => item.activity.activityID)
            const delGiftIDs = gifts.filter(item => !currentActivityIDs.includes(item.activityID)).map(item => item.activityGoodsGiftID)  //需要删除的赠品id集合
            //console.log(delGiftIDs)
            //console.log(shoppingCarData.value[currentActiveVariableIndex.value])
            shoppingCarData.value[currentActiveVariableIndex.value] = shoppingCarData.value[currentActiveVariableIndex.value].filter(item => {
                //console.log(!delGiftIDs.includes(item.activityGoodsGiftID))
                return !delGiftIDs.includes(item.activityGoodsGiftID)
            })
        } else {//删除所有赠品
            //console.log('删除所有赠品')
            shoppingCarData.value[currentActiveVariableIndex.value] = shoppingCarData.value[currentActiveVariableIndex.value].filter(item => !item.isGift)
        }

    })



    delRowDialogVisible.value = false
}

//清空 删除订单
function clear() {
    clearDialogVisible.value = true
}
function confirmClear() {
    shoppingCarData.value[currentActiveVariableIndex.value] = []
    currentShoppingCarPageNo.value = 1
    clearDialogVisible.value = false
    //清除优惠券抵扣金额
    currentCouponDiscountPrice.value = 0
}


const currentPayTypePageNo = ref(1)
const payTypePageSize = ref(12)
//当前支付方式分页后的数据
const currentPayTypeData = computed(() => {
    return paginateData(payTypeList.value, payTypePageSize.value) || []

})
//console.log(currentPayTypeData)


//结算
function handleSettlement() {
    // console.log(payTypeTable.value)
    isShowPayKeyboard.value = true


    // nextTick(()=>{

    // })
}
//结算弹窗关闭后，清空payTypeTable(防止后面修改购物车商品)
watch(() => isShowPayKeyboard.value, (newVal) => {
    if (!newVal) {
        payTypeTable.value = []
        currentPayType.value = null
    }
})
function payDialogOpened() {
    //设置输入框的值默认为应付金额
    //console.log(computedUnreceivePrice.value)
    currentPayInput.value = computedUnreceivePrice.value + ''

    isPayInputSelect.value = true //打开弹窗后输入框被选中
    nextTick(() => {
        // console.log(computedUnreceivePrice.value)
        //设置键盘金额
        payKeboardRef.value && payKeboardRef.value.setKeyboardInput(computedUnreceivePrice.value + '')  //注意这里setKeyboardInput 一定要使用字符串

    })

}
//原价
const orderTotalPrice = computed(() => {

    const totalPrice = shoppingCarData.value[currentActiveVariableIndex.value].reduce((prev, currentVal) => {
        return NP.plus(prev, roundNumber(NP.times(currentVal.quantity, currentVal.basicPrice)))
    }, 0)

    return totalPrice
})

//应收金额 = 小计之和(不排除赠品) - 优惠券抵扣
const computedReceivePrice = computed(() => {

    // console.log('应收')
    // console.log( shoppingCarData.value[currentActiveVariableIndex.value])
    // console.log( shoppingCarData.value[currentActiveVariableIndex.value].filter(item => !item.isGift))

    let totalPrice = shoppingCarData.value[currentActiveVariableIndex.value].reduce((prev, currentVal) => {

        //如果是会员专享，并且未登录会员，此时的金额是basicPrice
        if (currentVal.retailPrice < currentVal.basicPrice && currentVal.useUser === '2' && !currentMemberInfo.value) {
            return roundNumber(plus(prev, times(currentVal.basicPrice, currentVal.quantity)))
        } else {

            return roundNumber(plus(prev, times(currentVal.retailPrice, currentVal.quantity)))
        }

    }, 0)

    totalPrice = minus(totalPrice, unPriceTypeDiscountTotal.value)

    if (currentCouponDiscountPrice.value > totalPrice) {
        return 0
    } else {
        return NP.minus(totalPrice, currentCouponDiscountPrice.value)
    }

})

//未付金额 （应付金额 - 支付方式列表总金额）
const computedUnreceivePrice = computed(() => {
    let total = payTypeTable.value.reduce((prev, currentVal) => {
        return NP.plus(prev, currentVal.payAmount ? currentVal.payAmount : 0, currentVal.giveCash ? currentVal.giveCash : 0) //这里使用 giveCash有可能是会员扫码使用了余额
    }, 0)

    return NP.minus(computedReceivePrice.value, total)

})
//找零 (当前输入金额 - 未付金额)
const computedGiveChange = computed(() => {
    if (NP.minus(currentPayInput.value === '' ? 0 : currentPayInput.value, computedUnreceivePrice.value) < 0) {
        return ''
    }
    return NP.minus(currentPayInput.value === '' ? 0 : currentPayInput.value, computedUnreceivePrice.value)

})



//
function onPayKeyboardChange(val) {
    //console.log(val)
    if (currentPayType.value?.pkey == SHOPPINGCARDKEY) { //购物卡
        currentShoppingCardNo.value = val
    } else {
        currentPayInput.value = val
    }

}

//处理购物卡扫码
async function scanShoppingCard(cardNo) {
    if (payTypeTable.value) { //重复输入同一卡号
        const index = payTypeTable.value.findIndex(item => item.isShoppingCard && item.shoppingCardID == cardNo)
        if (index !== -1) {
            ElMessage({
                message: '购物卡卡号重复',
                type: 'error',
            })
            return
        }
    }
    try {
        const { data } = await getShoppingCardBalance(cardNo, shopID)
        const balance = data
        if (!balance || balance == 0) {
            ElMessage({
                message: '购物卡余额不足',
                type: 'error',
            })
            return
        }
        /*购物卡余额 大于等于未付金额 结算完成创建订单,否则payTypeTable添加一条支付方式 */
        if (NP.minus(balance, computedUnreceivePrice.value * 1) >= 0) {
            payTypeTable.value.unshift({ ...currentPayType.value, payAmount: computedUnreceivePrice.value * 1, isShoppingCard: true, shoppingCardID: cardNo, cardBalance: NP.minus(balance, computedUnreceivePrice.value * 1) })
            await toCreateOrder()
        } else {
            payTypeTable.value.unshift({ ...currentPayType.value, payAmount: balance, isShoppingCard: true, shoppingCardID: cardNo, cardBalance: 0 })

        }

        currentPayInput.value = ''   //重置输入框的值
        payKeboardRef.value && payKeboardRef.value.setKeyboardInput('') //重置键盘值
        //清除当前选中支付方式
        currentPayType.value = null
    } catch (error) {

    } finally {

    }

}


//确定支付输入金额/输入购物卡号
async function confirmPayInput() {
    // console.log('confirmPayInput!')
    if (!currentPayType.value) {
        ElMessage({
            message: '请选择支付方式',
            type: 'error',
        })
        return
    }

    if (currentPayType.value?.pkey === SHOPPINGCARDKEY) { //购物卡
        if (!currentShoppingCardNo.value) {
            ElMessage({
                message: '请输入卡号',
                type: 'error',
            })
            return
        }
        if (payTypeTable.value) { //重复输入同一卡号
            const index = payTypeTable.value.findIndex(item => item.isShoppingCard && item.shoppingCardID == currentShoppingCardNo.value)
            if (index !== -1) {
                ElMessage({
                    message: '购物卡卡号重复',
                    type: 'error',
                })
                return
            }
        }

        try {
            const { data } = await getShoppingCardBalance(currentShoppingCardNo.value, shopID)
            const balance = data
            if (!balance || balance == 0) {
                ElMessage({
                    message: '购物卡余额不足',
                    type: 'error',
                })
                return
            }
            /*购物卡余额 大于等于未付金额 结算完成创建订单,否则payTypeTable添加一条支付方式 */
            if (NP.minus(balance, computedUnreceivePrice.value * 1) >= 0) {
                payTypeTable.value.unshift({ ...currentPayType.value, payAmount: computedUnreceivePrice.value * 1, isShoppingCard: true, shoppingCardID: currentShoppingCardNo.value, cardBalance: NP.minus(balance, computedUnreceivePrice.value * 1) })
                await toCreateOrder()
            } else {
                payTypeTable.value.unshift({ ...currentPayType.value, payAmount: balance, isShoppingCard: true, shoppingCardID: currentShoppingCardNo.value, cardBalance: 0 })

            }


            currentPayInput.value = ''   //重置输入框的值
            payKeboardRef.value && payKeboardRef.value.setKeyboardInput('') //重置键盘值
            //清除当前选中支付方式
            currentPayType.value = null
        } catch (error) {

        }



    } else {
        if (!currentPayInput.value) {
            ElMessage({
                message: '请输入金额',
                type: 'error',
            })
            return
        }

        /*输入金额大于等于未付金额 结算完成创建订单,否则payTypeTable添加一条支付方式 */
        if (NP.minus(currentPayInput.value, computedUnreceivePrice.value) >= 0) {
            //console.log('结算已完成')
            payTypeTable.value.unshift({ ...currentPayType.value, payAmount: computedUnreceivePrice.value })
            await toCreateOrder()
        } else {
            payTypeTable.value.unshift({ ...currentPayType.value, payAmount: currentPayInput.value })
        }


        currentPayInput.value = ''   //重置输入框的值
        payKeboardRef.value && payKeboardRef.value.setKeyboardInput('') //重置键盘值
        //确定后去掉输入框选中样式
        if (isPayInputSelect.value) {
            isPayInputSelect.value = false
        }

        //清除当前选中支付方式
        currentPayType.value = null
    }



}
//电子支付弹窗关闭后 从payTypeTable中删除第一条记录

watch(() => isShowElectronicDialog.value, (newVal) => {
    // console.log(newVal)
    if (!newVal) {

        currentPayType.value = null
    }
})

//删除支付方式行
function delPayTypeRow(index) {
    //console.log(index)
    payTypeTable.value.splice(index, 1)
}


//切换支付方式
function changePayType(item) {
    authCode.value = ''
    //console.log(isOnline.value)
    if (!isOnline.value && offlineUnusablePayTypeList.value.includes(item.pkey)) {
        ElMessage({
            message: '离线模式不可使用此支付方式',
            type: 'error'
        })
        return false
    }
    currentPayType.value = item
    if (item.pkey === 'OP_GC') { //购物卡 清除输入金额的值
        currentPayInput.value = ''
        currentShoppingCardNo.value = ''
        payKeboardRef.value && payKeboardRef.value.setKeyboardInput('')
    } else { //非购物卡 计算剩余应付金额，并将键盘的值重新赋值
        // currentPayInput.value = computedUnreceivePrice.value + ''
        // payKeboardRef.value && payKeboardRef.value.setKeyboardInput(currentPayInput.value)
        if (item.pkey === 'EP') { //电子支付 这里注释了TODOTO
            // console.log('电子支付')
            // console.log({ ...currentPayType.value })
            // payTypeTable.value.unshift({ ...currentPayType.value, payAmount: computedUnreceivePrice.value })
            currentPayInput.value = ''

            payKeboardRef.value && payKeboardRef.value.setKeyboardInput('')
            isShowElectronicDialog.value = true
        } else if (item.pkey === 'MB') { //会员支付

            // payTypeTable.value.unshift({ ...currentPayType.value, payAmount: computedUnreceivePrice.value })
            currentPayInput.value = ''

            payKeboardRef.value && payKeboardRef.value.setKeyboardInput('')
            isShowElectronicDialog.value = true
        } else {
            currentPayInput.value = computedUnreceivePrice.value + ''
            payKeboardRef.value && payKeboardRef.value.setKeyboardInput(currentPayInput.value)
        }
    }



}

//
function payIndexMethod(index) {
    return payTypeTable.value.length - index
}

//按键
function onPayKeyboardKeyPress(btn) {


    //console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, '.', 0, '{bksp}'].find(item => item == btn))
    //点击右侧快捷金额时，清空键盘值
    if (([1, 2, 3, 4, 5, 6, 7, 8, 9, '.', 0, '{bksp}'].find(item => item == btn)) === undefined) {
        // console.log('重置')
        payKeboardRef.value && payKeboardRef.value.setKeyboardInput('') //重置键盘值
    }

    if (isPayInputSelect.value) { //输入框值被选中 则所有操作都是重置
        payKeboardRef.value && payKeboardRef.value.setKeyboardInput('') //重置键盘值
    }

    //按键后 去掉选中样式
    isPayInputSelect.value = false
}

watch(() => payTypeTable.value, (newVal) => {
    // console.log('payTypeTableBianhuale~')
    // console.log(newVal)
}, { deep: true })

//创建订单
async function toCreateOrder(payType) {

    //console.log(currentActivityDiscountData.value)
    //   memberCouponPOSDtos:Array<any> //订单创建优惠券
    //   memberCouponIDs:Array<any> //使用会员优惠券id
    let memberID = null
    let memberPhoneNumber = null
    if (currentMemberInfo.value) {
        memberID = currentMemberInfo.value.id
        memberPhoneNumber = currentMemberInfo.value.phoneNumber
    }






    //商品件数
    const goodsQuantity = computedVariableNums.value(currentActiveVariableIndex.value)
    //console.log(payTypeTable.value[0].payAmount)
    let payAmount = 0
    if (payType && payType == 'EP') { //电子支付
        const EPItem = payTypeList.value.find(item => item.pkey === 'EP')
        payTypeTable.value.unshift({ ...EPItem, payAmount: computedUnreceivePrice.value })
        payAmount = payTypeTable.value[0].payAmount
    }


    const orderPayDto = {
        authCode: authCode.value, //付款码
        payAmount: payAmount, //网络支付金额
        orderPayAddDtos: payTypeTable.value.map(item => {
            if (item.isShoppingCard) { //购物卡
                return {
                    payType: item.pkey,
                    payTypeText: item.pvalue,
                    payAmount: item.payAmount,
                    shoppingCardID: item.shoppingCardID
                }
            } else {
                return { payType: item.pkey, payTypeText: item.pvalue, payAmount: item.payAmount, giveCash: item.giveCash || 0 }
            }

        })
    }


    let orderDetailAddDtos = shoppingCarData.value[currentActiveVariableIndex.value].map(item => {

        //原金额

        const originalPrice = roundNumber(NP.times(item.quantity, item.basicPrice))
        //活动优惠金额
        let activityDiscountPrice = 0

        if (item.priceActivityID) { //价格类型活动

            const index = currentActivityDiscountData.value.findIndex(childItem => childItem.activity && childItem.activity.activityID === item.priceActivityID)
            if (index !== -1) {
                //找到优惠明细中的该商品
                const goods = currentActivityDiscountData.value[index].goods.find(good => good.goodsID === item.goodsID && good.currentTime === item.currentTime)
                if (goods) {
                    // console.log('价格类型优惠金额', goods.activityDiscount)
                    item.priceTypeActivityDiscount = goods.activityDiscount //添加价格类型优惠，后续打印小票使用
                    activityDiscountPrice = NP.plus(activityDiscountPrice, goods.activityDiscount)
                }

            }
        }
        if (item.otherActivityID) { //非价格类型活动

            const index = currentActivityDiscountData.value.findIndex(childItem => childItem.activity && childItem.activity.activityID === item.otherActivityID)
            if (index !== -1) {

                //找到优惠明细中的该商品
                const goods = currentActivityDiscountData.value[index].goods.find(good => good.goodsID === item.goodsID && good.currentTime === item.currentTime)

                if (goods) {
                    // console.log(2573)
                    // console.log(goods)
                    //console.log('非价格类型优惠金额', goods.activityDiscount)
                    if (currentActivityDiscountData.value[index].activity.type !== '11') { //排除赠品（赠品优惠不计算到各个商品上）
                        activityDiscountPrice = NP.plus(activityDiscountPrice, goods.activityDiscount)
                    }



                }



            }
        }

        const payAmount = NP.minus(originalPrice, activityDiscountPrice)//优惠后的金额
        return { ...item, activityDiscount: activityDiscountPrice, payAmount, originalPrice, couponDiscount: 0 }
    })


    //计算每个品的优惠券优惠额度
    //找到优惠明细中的优惠券，循环优惠券优惠的商品
    //console.log(shoppingCarData.value[currentActiveVariableIndex.value])
    let memberCouponIDs = [] //会员使用优惠券ID集合
    const couponIndex = currentActivityDiscountData.value.findIndex(item => item.isCoupon)
    if (couponIndex == -1) {
        //console.log('没有使用优惠券')
        memberCouponIDs = []
    } else {
        orderDetailAddDtos = orderDetailAddDtos.map(item => {
            //找到优惠券中的该商品
            const goods = currentActivityDiscountData.value[couponIndex].goods.find(good => good.goodsID === item.goodsID && good.currentTime === item.currentTime)
            if (goods) {

                //console.log('优惠券优惠金额', goods.activityDiscount)
                item.couponDiscount = goods.activityDiscount //在addActivityDiscountLog时 优惠券中每个商品的优惠也是activityDiscount
                item.payAmount = NP.minus(item.originalPrice, item.activityDiscount, goods.activityDiscount)
                item.memberCouponID = currentUsingCoupon.value.memberCouponID
                item.couponID = currentUsingCoupon.value.couponID
            }
            return { ...item }
        })
        if (currentUsingCoupon.value) {
            memberCouponIDs.push(currentUsingCoupon.value.memberCouponID)
        }

    }
    //console.log(orderDetailAddDtos)
    let memberCouponPOSDtos = [] //订单创建 发券列表

    //创建订单可发放的优惠券，将适用商品集合放到优惠券上
    if (memberID) {
        // console.log(createOrderDeliverCoupons.value)
        for (let item of createOrderDeliverCoupons.value) {
            if (item.rule === 0) { //无门槛
                memberCouponPOSDtos.push({
                    memberID,
                    couponID: item.couponID,
                    distributionQuantity: item.distributionQuantity,
                    dayReceiveLimit: item.dayReceiveLimit,
                    totalReceiveLimit: item.totalReceiveLimit,
                    couponQuantity: item.couponQuantity,
                    startUseTime: item.startUseTime,
                    endUseTime: item.endUseTime

                })
            } else {

                item.goods = []
                for (let childItem of orderDetailAddDtos) {
                    // console.log(childItem.deliverCouponIDs)
                    // console.log(item.couponDeliverID)
                    if (childItem.deliverCouponIDs && childItem.deliverCouponIDs.includes(item.couponDeliverID)) {
                        item.goods.push(childItem)
                    }
                }

                //求适用商品支付总金额
                let totalPrice = item.goods.reduce((prev, currentVal) => {
                    return NP.plus(prev, currentVal.payAmount)
                }, 0)

                if (totalPrice > item.rule) { //订单满rule 发券
                    memberCouponPOSDtos.push({
                        memberID,
                        couponID: item.couponID,
                        distributionQuantity: item.distributionQuantity,
                        dayReceiveLimit: item.dayReceiveLimit,
                        totalReceiveLimit: item.totalReceiveLimit,
                        couponQuantity: item.couponQuantity,
                        startUseTime: item.startUseTime,
                        endUseTime: item.endUseTime

                    })
                }

                // console.log(item.goods)
            }
        }
    }

    //console.log(memberCouponPOSDtos)


    //console.log(priceSchemesID.value)
    const priceType = currentPriceType.value
    const priceTypeText = allGoodsData.value.find(item => item.priceType === priceType).priceTypeText
    const reqData = {
        priceSchemesID: priceSchemesID.value,
        saleOrganizationID,
        shopID,
        shopCode: shopInfo.value.shopCode,
        shopName,
        memberID,
        memberPhoneNumber,
        originalAmount: orderTotalPrice.value,
        receivableAmount: computedReceivePrice.value,
        discountAmount: NP.plus(currentTotalActivityDiscount.value, currentCouponDiscountPrice.value),
        goodsQuantity,
        orderTime: getTimeString(currentTime.value),
        orderPayDto,
        orderDetailAddDtos: orderDetailAddDtos.map(item => ({ ...item, isGift: item.isGift ? 1 : 0, payAmount: item.isGift ? 0 : item.payAmount })),
        priceType,
        priceTypeText,
        memberCouponPOSDtos,
        memberCouponIDs


    }
    //console.log(reqData)
    // console.log(reqData.orderTime)

    try {

        if (isOnline.value) {
            const { data, msg, code } = await createOrder(reqData)
            if (code == 0 && data.state && data.state == 0) {
                ElMessage({
                    message: '订单已保存为待支付状态，请确认客人是否已付款',
                    type: 'success',
                    duration: 5000
                })

                clearData()

            } else {
                payTicketInfo.value = { orderNO: data.orderNO, reqData, sumRemainingBalance: data.sumRemainingBalance, remainingShoppingCardVos: data.remainingShoppingCardVos } //打印小票用数据
                // console.log(payTicketInfo.value)
                // return 
                if (data.accountType) {
                    let speakText = `${electronicPayTypeList[data.accountType]}收款${reqData.orderPayDto.payAmount}元`
                    speak(speakText)
                }

                ElMessage({
                    message: msg,
                    type: 'success',
                })

                printTicket({ type: 'order', orderNum: data.orderNO })
            }



        } else { //离线模式
            // let offineID = uuidv4().replace(/-/g, "");
            let offineID = getOfflineId();
            //console.log(offineID)

            //  console.log(offineID)
            window.electron.ipcRenderer.send('insert-order', {
                offineID,
                priceSchemesID: priceSchemesID.value,
                saleOrganizationID,
                shopID,
                shopCode: shopInfo.value.shopCode,
                shopName,
                originalAmount: JSON.stringify(orderTotalPrice.value),
                receivableAmount: computedReceivePrice.value,
                discountAmount: NP.plus(currentTotalActivityDiscount.value, currentCouponDiscountPrice.value),
                goodsQuantity,
                orderTime: getTimeString(currentTime.value),
                orderPayDto: JSON.stringify(orderPayDto),
                orderDetailAddDtos: JSON.stringify(orderDetailAddDtos),
                priceType,
                priceTypeText,
                memberCouponPOSDtos: JSON.stringify(memberCouponPOSDtos)
            })
            ElMessage({
                message: '离线订单创建已完成',
                type: 'success',
            })
            payTicketInfo.value = { orderNO: offineID, reqData, } //打印小票用数据
            printTicket({ type: 'order', orderNum: offineID })

        }


    } catch (error) {
        console.log(error)
        //创建订单出错时 删除第一条记录
        payTypeTable.value.splice(0, 1)
    } finally {
        isShowElectronicDialog.value = false
        currentPayType.value = null
    }






}


//副屏传输数据
function transferSecondWindow(shoppingCarData) {
    let transferData = {}
    let transferArr = []
    for (let item of shoppingCarData[currentActiveVariableIndex.value]) {
        let rowPrice = 0 //小计
        let singlePrice = 0
        if (item.retailPrice < item.basicPrice && item.useUser === '2' && !currentMemberInfo.value) { //会员专享 未登录会员
            singlePrice = item.basicPrice
            rowPrice = roundNumber(plus(times(item.basicPrice, item.quantity)))
        } else {
            singlePrice = item.retailPrice
            rowPrice = roundNumber(plus(times(item.retailPrice, item.quantity)))
        }

        transferArr.push({ singlePrice, goodsName: item.goodsName, quantity: item.quantity, rowPrice, isGift: item.isGift })
    }
    let shouldReceivePrice = computedReceivePrice.value //应收
    let activityDiscountPrice = currentTotalActivityDiscount.value //活动优惠
    const couponDiscountPrice = currentCouponDiscountPrice.value //优惠券抵扣
    transferData.list = transferArr
    transferData.shouldReceivePrice = shouldReceivePrice
    transferData.activityDiscountPrice = activityDiscountPrice
    transferData.couponDiscountPrice = couponDiscountPrice
    // console.log(transferData)
    const stringfyData = JSON.stringify(transferData)
    window.electron.ipcRenderer.send('secondwindow-shoppingcardata', stringfyData)
}


//shoppingCarData 改变时调用store中的方法 重新设置值，存储到localStorage中
watch(() => shoppingCarData.value, (newVal) => {
    //  console.log('shoppingCarData变化了 重新设置')
    //  console.log(newVal)
    for (let item of newVal[currentActiveVariableIndex.value]) {
        //判断价格类型商品是否在生效时间内，如果不在生效时间内 则设置retailPrice的值为basicPrice
        if (item.priceActivityID) {
            if (item.retailPrice < item.basicPrice && !isActiveInUsableTime(item.priceActivityID, priceActivitys.value, currentTime.value)) {
                item.retailPrice = item.basicPrice

            }
        }

    }
    //console.log(newVal)



    userStore.setShoppingCarData(shoppingCarData.value)
    //计算活动优惠
    calculateActivityDiscount()

    //console.log('')
    //计算可用优惠券
    calculateUsableCouponAndUnusableCoupon()
    //计算优惠券明细
    calculateCouponDiscountPrice()

    //数据变化 向副屏传递数据
    transferSecondWindow(newVal)
}, { deep: true, immediate: true })
watch(() => currentActiveVariableIndex.value, (newVal) => {

    transferSecondWindow(shoppingCarData.value)

}, { deep: true, immediate: true })

watch(() => currentCouponDiscountPrice.value, (newVal) => {

    transferSecondWindow(shoppingCarData.value)

}, { deep: true, immediate: true })


//监视 allData 数据获取后，改变购物车数据（因为购物车数据是缓存到localstorage里的，这里循环对比，替换为新数据）
watch(() => allData.value, (newVal) => {
    // console.log('watch new val')
    for (let i = 0; i < shoppingCarData.value.length; i++) {
        for (let j = 0; j < shoppingCarData.value[i].length; j++) {
            const found = saleGoodsData.value.find(item => item.goodsID === shoppingCarData.value[i][j].goodsID)
            //  console.log(found)
            if (found) {
                shoppingCarData.value[i][j] = { ...found, quantity: shoppingCarData.value[i][j].quantity, currentTime: shoppingCarData.value[i][j].currentTime, isGift: shoppingCarData.value[i][j].isGift }
                //如果是赠品 需要修改它的activityID 属性的值 为shoppingCarData.value[i][j]的otherActivityID，因为后续计算赠品活动需要activityID 属性的值
                if (shoppingCarData.value[i][j].isGift) {
                    shoppingCarData.value[i][j].activityID = shoppingCarData.value[i][j].otherActivityID
                }
            }

        }

    }


    //计算活动优惠
    calculateActivityDiscount()


    //计算可用优惠券
    calculateUsableCouponAndUnusableCoupon()
    //计算优惠券明细
    calculateCouponDiscountPrice()

}, { deep: true, immediate: true })

//是否显示赠品按钮
const isShowGiftBtn = computed(() => {
    return currentGoodsGiftAndActivitys.value.length > 0

})

//添加优惠明细记录
function addActivityDiscountLog(data) {
    // console.log('添加优惠明细记录！')
    // console.log(data)
    currentActivityDiscountData.value.push(data)
    //console.log(currentActivityDiscountData.value)
}

//计算按活动分组后 每个分组商品的总金额
function calculateActivityGroupTotalPrice(groupGoods) {
    return groupGoods.reduce((prev, currentVal) => { //计算总金额(数量*降价后的金额)
        //如果是会员专享，并且未登录会员，此时的金额是basicPrice
        if (currentVal.retailPrice < currentVal.basicPrice && currentVal.useUser === '2' && !currentMemberInfo.value) {
            return NP.plus(prev, roundNumber(NP.times(currentVal.basicPrice, currentVal.quantity)))
        } else {
            return NP.plus(prev, roundNumber(NP.times(currentVal.retailPrice, currentVal.quantity)))
        }

    }, 0)
}

//计算每个分组商品 除最后一个商品的 活动优惠金额总合
function calculateTotalActiveDiscountExcludeLast(groupGoods, totalPrice, totalDiscountPrice) {
    return groupGoods.slice(0, -1).reduce((prev, currentVal) => {
        let currentGoodsTotalPrice = roundNumber(NP.times(currentVal.retailPrice, currentVal.quantity))
        let currentDiscount = roundNumber(NP.times(NP.divide(currentGoodsTotalPrice, totalPrice), totalDiscountPrice))
        return NP.plus(prev, currentDiscount)
    }, 0)
}

//计算每个分组商品  每个品的优惠
function calculateEveryGoodsDiscount(groupGoods, totalPrice, totalDiscountPrice, totalActiveDiscountExcludeLast) {
    return groupGoods.map((item, index) => {
        if (index === groupGoods.length - 1) { //最后一位的优惠 = 总优惠-之前商品的优惠总额 （打折可能会除不开）
            return { ...item, activityDiscount: NP.minus(totalDiscountPrice, totalActiveDiscountExcludeLast) }
        }
        let currentGoodsTotalPrice = roundNumber(NP.times(item.retailPrice, item.quantity))
        let currentDiscount = roundNumber(NP.times(NP.divide(currentGoodsTotalPrice, totalPrice), totalDiscountPrice))

        return { ...item, activityDiscount: currentDiscount }
    })
}

//计算每个分组商品 总件数
function calculateGroupGoodsTotalPiece(groupGoods) {
    return groupGoods.reduce((prev, currentVal) => { //计算总件数
        return NP.plus(prev, currentVal.isQuantityUnit === 'y' ? currentVal.quantity : 1)
    }, 0)
}

//筛选掉不在活动生效时间内的商品

function filterNotInTimeGoods(activitys, goods, activityIdKey) {
    return goods.filter(item => {
        return isActiveInUsableTime(item[activityIdKey], activitys, item.currentTime)
    })
}

//判断使用用户是否满足条件
function isUserStatusValid(status, memberInfo) { //1、全部 2、全部会员 3、充值会员
    if (status === '1') return true;

    if (status === '2' && memberInfo !== null) return true;

    if (status === '3' && memberInfo !== null && memberInfo.isRecharge === '1') return true;

    return false; // 其他情况返回false
}

//计算活动优惠 和 赠品
function calculateActivityDiscount() {
    // console.log('`计算活动优惠和赠品')
    //重置赠品活动值
    currentGoodsGiftAndActivitys.value = []
    //重置优惠明细
    currentActivityDiscountData.value = []

    let goodsList = shoppingCarData.value[currentActiveVariableIndex.value]

    let priceTypeGoods = goodsList.filter(item => item.retailPrice < item.basicPrice) || [] //价格类型活动商品
    let unPriceTypeGoods = goodsList.filter(item => item.otherActivityID !== null) || [] //非价格类型活动商品
    //console.log(unPriceTypeGoods)

    //console.log(priceTypeGoods)
    let priceTypeDiscount = 0 //价格类型活动商品 折扣金额总合
    //筛选掉不在生效时段内的价格类型活动商品
    priceTypeGoods = filterNotInTimeGoods(priceActivitys.value, priceTypeGoods, 'priceActivityID')
    //价格活动按活动id分组
    // console.log(priceTypeGoods)
    const priceGroupDataObj = groupByKey(priceTypeGoods, 'priceActivityID')
    // console.log(priceGroupDataObj)
    for (let key in priceGroupDataObj) {
        const foundActivity = priceActivitys.value.find(activityItem => activityItem.activityID === key)
        //console.log(foundActivity)
        const { type } = foundActivity
        if (type === '9') { //价格直降
            // console.log(`'价格直降！`)
            const useUser = foundActivity.useUser

            if (isUserStatusValid(useUser, currentMemberInfo.value)) {//判断使用用户 1、全部2、全部会员3、充值会员
                //计算每个品的 活动优惠 
                let mapGoods = priceGroupDataObj[key].map((item, index) => {
                    return { ...item, activityDiscount: NP.minus(roundNumber(NP.times(item.basicPrice, item.quantity)), roundNumber(NP.times(item.retailPrice, item.quantity))) }
                })
                //计算总优惠
                let totalDiscountPrice = mapGoods.reduce((prev, currentVal) => {
                    return plus(prev, currentVal.activityDiscount)
                }, 0)
                //  console.log('总优惠！', totalDiscountPrice)
                priceTypeDiscount = NP.plus(priceTypeDiscount, totalDiscountPrice)
                //console.log(priceGroupDataObj[key]) 
                addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `直降`, discountPrice: totalDiscountPrice })
            }
            //console.log(currentActivityDiscountData.value)
        } else if (type === '10') { //价格折扣
            //console.log(`'价格折扣！`)
            const useUser = foundActivity.useUser
            if (isUserStatusValid(useUser, currentMemberInfo.value)) {
                //计算每个品的 活动优惠 
                let mapGoods = priceGroupDataObj[key].map((item, index) => {
                    return { ...item, activityDiscount: NP.minus(roundNumber(NP.times(item.basicPrice, item.quantity)), roundNumber(NP.times(item.retailPrice, item.quantity))) }
                })
                //计算总优惠
                let totalDiscountPrice = mapGoods.reduce((prev, currentVal) => {
                    return plus(prev, currentVal.activityDiscount)
                }, 0)
                priceTypeDiscount = NP.plus(priceTypeDiscount, totalDiscountPrice)
                //console.log(priceGroupDataObj[key])
                addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `${foundActivity.discount}折`, discountPrice: totalDiscountPrice })
            }
            //console.log(currentActivityDiscountData.value)
        }
    }


    let unPriceTypeDiscount = 0 //非价格类型活动优惠总额
    //筛选掉不在生效时段内的非价格类型活动商品
    unPriceTypeGoods = filterNotInTimeGoods(otherActivitys.value, unPriceTypeGoods, 'otherActivityID')
    //其它活动按活动id分组
    //console.log(unPriceTypeGoods)
    const unPriceGroupDataObj = groupByKey(unPriceTypeGoods, 'otherActivityID')
    // console.log(unPriceGroupDataObj)
    //console.log(unPriceTypeDiscount)
    for (let key in unPriceGroupDataObj) {
        const foundActivity = otherActivitys.value.find(activityItem => activityItem.activityID === key)
        //console.log(foundActivity)
        const { type } = foundActivity

        if (type === '5') { //满额折扣
            // console.log(`'满额折扣！`)
            const useUser = foundActivity.useUser
            if (isUserStatusValid(useUser, currentMemberInfo.value)) {

                const rule = foundActivity.rule
                const discount = NP.minus(1, NP.divide(foundActivity.discount, 10))  //折扣(1减去折扣)
                //计算总金额
                let totalPrice = calculateActivityGroupTotalPrice(unPriceGroupDataObj[key])

                if (rule === 0 || totalPrice > rule) {
                    //计算总优惠金额
                    let totalDiscountPrice = roundNumber(NP.times(totalPrice, discount))
                    //计算 除最后一个商品的 活动优惠金额总合 每个品按该商品金额占该活动总金额的 比例分配优惠 （某商品总金额/当前活动总金额 * 总优惠金额）
                    let totalActiveDiscountExcludeLast = calculateTotalActiveDiscountExcludeLast(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice)
                    //计算每个品的 活动优惠 
                    let mapGoods = calculateEveryGoodsDiscount(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice, totalActiveDiscountExcludeLast)
                    if (rule === 0) { //判断活动规则(0 无门槛)
                        unPriceTypeDiscount = NP.plus(unPriceTypeDiscount, NP.times(totalPrice, discount))
                        addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `无门槛 打${foundActivity.discount}折`, discountPrice: totalDiscountPrice })
                    } else {//订单满rule 元 打xxx折  
                        if (totalPrice > rule) {
                            unPriceTypeDiscount = NP.plus(unPriceTypeDiscount, NP.times(totalPrice, discount))
                            addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `满${rule} 打${foundActivity.discount}折`, discountPrice: totalDiscountPrice })
                        }
                    }
                }
            }
            //console.log(currentActivityDiscountData.value)
        } else if (type === '6') {//满件折扣
            //console.log(`'满件折扣！`)
            const useUser = foundActivity.useUser
            if (isUserStatusValid(useUser, currentMemberInfo.value)) {
                const rule = foundActivity.rule
                let totalPiece = calculateGroupGoodsTotalPiece(unPriceGroupDataObj[key])
                if (rule === 0 || totalPiece >= rule) {
                    const discount = NP.minus(1, NP.divide(foundActivity.discount, 10))  //折扣(1减去折扣)
                    let totalPrice = calculateActivityGroupTotalPrice(unPriceGroupDataObj[key])
                    //计算总优惠金额
                    let totalDiscountPrice = roundNumber(NP.times(totalPrice, discount))
                    //计算 除最后一个商品的 活动优惠金额总合 每个品按该商品金额占该活动总金额的 比例分配优惠 （某商品总金额/当前活动总金额 * 总优惠金额）
                    let totalActiveDiscountExcludeLast = calculateTotalActiveDiscountExcludeLast(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice)
                    //计算每个品的 活动优惠  
                    let mapGoods = calculateEveryGoodsDiscount(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice, totalActiveDiscountExcludeLast)

                    if (rule === 0) { //判断活动规则(0 无门槛)
                        unPriceTypeDiscount = NP.plus(unPriceTypeDiscount, NP.times(totalPrice, discount))
                        addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `无门槛 打${foundActivity.discount}折`, discountPrice: NP.times(totalPrice, discount) })
                    } else { //订单满rule件 打xxx折  
                        if (totalPiece >= rule) {
                            unPriceTypeDiscount = NP.plus(unPriceTypeDiscount, NP.times(totalPrice, discount))
                            addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `满${rule}件 打${foundActivity.discount}折`, discountPrice: NP.times(totalPrice, discount) })
                        }

                    }
                }



            }
        } else if (type === '1') { //金额满减
            // console.log(`'金额满减！`)
            const useUser = foundActivity.useUser
            if (isUserStatusValid(useUser, currentMemberInfo.value)) {//判断使用用户 1、全部2、全部会员3、充值会员

                const rule = foundActivity.rule
                let totalPrice = calculateActivityGroupTotalPrice(unPriceGroupDataObj[key])
                if (rule === 0 || totalPrice >= rule) {
                    //计算总优惠金额
                    let totalDiscountPrice = foundActivity.discount
                    //计算 除最后一个商品的 活动优惠金额总合
                    let totalActiveDiscountExcludeLast = calculateTotalActiveDiscountExcludeLast(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice)
                    //计算每个品的 活动优惠  
                    let mapGoods = calculateEveryGoodsDiscount(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice, totalActiveDiscountExcludeLast)
                    //  console.log(mapGoods)
                    //  console.log(shoppingCarData.value[currentActiveVariableIndex.value])

                    if (rule === 0) { //判断活动规则(0 无门槛)
                        unPriceTypeDiscount = NP.plus(unPriceTypeDiscount, totalDiscountPrice)
                        addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `无门槛 减${totalDiscountPrice}`, discountPrice: totalDiscountPrice })
                    } else { //订单满rule 元 减xxx元  
                        if (totalPrice >= rule) {

                            //判断活动形式 是一次还是多次
                            const mode = foundActivity.mode
                            let modeText = ''
                            if (mode === '2') {//多次 (重新计算优惠)
                                totalDiscountPrice = NP.times(Math.floor(totalPrice / rule), totalDiscountPrice)
                                //计算 除最后一个商品的 活动优惠金额总合
                                let totalActiveDiscountExcludeLast = calculateTotalActiveDiscountExcludeLast(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice)
                                //计算每个品的 活动优惠  
                                mapGoods = calculateEveryGoodsDiscount(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice, totalActiveDiscountExcludeLast)
                                modeText = '多次'
                            }
                            unPriceTypeDiscount = NP.plus(unPriceTypeDiscount, totalDiscountPrice)
                            addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `满${rule} 减${foundActivity.discount} ${modeText}`, discountPrice: totalDiscountPrice })
                        }
                    }
                }


            }
        } else if (type === '2') { //件数满减
            //console.log(`'件数满减！`)
            const useUser = foundActivity.useUser
            if (isUserStatusValid(useUser, currentMemberInfo.value)) {

                const rule = foundActivity.rule
                let totalPiece = calculateGroupGoodsTotalPiece(unPriceGroupDataObj[key])
                if (rule === 0 || totalPiece >= rule) {
                    let totalPrice = calculateActivityGroupTotalPrice(unPriceGroupDataObj[key])
                    //计算总优惠金额
                    let totalDiscountPrice = foundActivity.discount
                    //计算 除最后一个商品的 活动优惠金额总合 
                    let totalActiveDiscountExcludeLast = calculateTotalActiveDiscountExcludeLast(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice)
                    //计算每个品的 活动优惠  
                    let mapGoods = calculateEveryGoodsDiscount(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice, totalActiveDiscountExcludeLast)

                    let discount = foundActivity.discount  //减的金额

                    if (rule === 0) { //判断活动规则(0 无门槛)
                        unPriceTypeDiscount = NP.plus(unPriceTypeDiscount, totalDiscountPrice)
                        addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `无门槛 减${totalDiscountPrice}`, discountPrice: totalDiscountPrice })
                    } else { //订单满rule 件 减xxx元  

                        if (totalPiece >= rule) {
                            //判断活动形式 是一次还是多次
                            const mode = foundActivity.mode
                            let modeText = ''
                            if (mode === '2') { //多次(重新计算优惠)
                                totalDiscountPrice = NP.times(Math.floor(totalPiece / rule), totalDiscountPrice)
                                //计算 除最后一个商品的 活动优惠金额总合
                                let totalActiveDiscountExcludeLast = calculateTotalActiveDiscountExcludeLast(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice)
                                //计算每个品的 活动优惠  
                                mapGoods = calculateEveryGoodsDiscount(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice, totalActiveDiscountExcludeLast)
                                modeText = '多次'
                            }
                            unPriceTypeDiscount = NP.plus(unPriceTypeDiscount, totalDiscountPrice)
                            addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `满${rule}件 减${foundActivity.discount} ${modeText}`, discountPrice: totalDiscountPrice })
                        }
                    }
                }


            }
        } else if (type === '7') { //阶梯金额折扣
            //console.log(`'阶梯金额折扣！`)
            const useUser = foundActivity.useUser
            if (isUserStatusValid(useUser, currentMemberInfo.value)) {//判断使用用户 1、全部2、全部会员3、充值会员
                //查找阶梯明细
                const stepDescArr = discountStep.value.filter(item => item.activityID === foundActivity.activityID)
                let totalPrice = calculateActivityGroupTotalPrice(unPriceGroupDataObj[key])
                for (let i = stepDescArr.length - 1; i >= 0; i--) { //倒序循环阶梯

                    if (totalPrice >= stepDescArr[i].rule) {
                        const discount = NP.minus(1, NP.divide(stepDescArr[i].reduction, 10))  //折扣(1减去折扣)

                        //计算总优惠金额
                        let totalDiscountPrice = roundNumber(NP.times(totalPrice, discount))
                        //计算 除最后一个商品的 活动优惠金额总合 每个品按该商品金额占该活动总金额的 比例分配优惠 （某商品总金额/当前活动总金额 * 总优惠金额）
                        let totalActiveDiscountExcludeLast = calculateTotalActiveDiscountExcludeLast(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice)
                        //计算每个品的 活动优惠  
                        let mapGoods = calculateEveryGoodsDiscount(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice, totalActiveDiscountExcludeLast)

                        unPriceTypeDiscount = NP.plus(unPriceTypeDiscount, totalDiscountPrice)
                        addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `满${stepDescArr[i].rule} 打${stepDescArr[i].reduction}折`, discountPrice: totalDiscountPrice })
                        break   //阶梯 跳出循环
                    }
                }

            }

        } else if (type === '8') { //阶梯件数折扣
            //console.log(`'阶梯件数折扣！`)
            const useUser = foundActivity.useUser
            if (isUserStatusValid(useUser, currentMemberInfo.value)) {//判断使用用户 1、全部2、全部会员3、充值会员
                //查找阶梯明细
                const stepDescArr = discountStep.value.filter(item => item.activityID === foundActivity.activityID)
                let totalPiece = calculateGroupGoodsTotalPiece(unPriceGroupDataObj[key])
                for (let i = stepDescArr.length - 1; i >= 0; i--) { //倒序循环阶梯
                    if (totalPiece >= stepDescArr[i].rule) {
                        let totalPrice = calculateActivityGroupTotalPrice(unPriceGroupDataObj[key])
                        const discount = NP.minus(1, NP.divide(stepDescArr[i].reduction, 10))  //折扣(1减去折扣)
                        //计算总优惠金额
                        let totalDiscountPrice = roundNumber(NP.times(totalPrice, discount))
                        //计算 除最后一个商品的 活动优惠金额总合 每个品按该商品金额占该活动总金额的 比例分配优惠 （某商品总金额/当前活动总金额 * 总优惠金额）
                        let totalActiveDiscountExcludeLast = calculateTotalActiveDiscountExcludeLast(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice)
                        //计算每个品的 活动优惠  
                        let mapGoods = calculateEveryGoodsDiscount(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice, totalActiveDiscountExcludeLast)

                        unPriceTypeDiscount = NP.plus(unPriceTypeDiscount, totalDiscountPrice)
                        addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `满${stepDescArr[i].rule}件 打${stepDescArr[i].reduction}折`, discountPrice: totalDiscountPrice })
                        break   //阶梯 跳出循环
                    }
                }

            }

        } else if (type === '3') { //阶梯金额满减
            //console.log(`'阶梯金额满减！`)
            const useUser = foundActivity.useUser
            if (isUserStatusValid(useUser, currentMemberInfo.value)) {
                //查找阶梯明细
                const stepDescArr = discountStep.value.filter(item => item.activityID === foundActivity.activityID)
                // console.log(stepDescArr)
                let totalPrice = calculateActivityGroupTotalPrice(unPriceGroupDataObj[key])

                for (let i = stepDescArr.length - 1; i >= 0; i--) { //倒序循环阶梯
                    //   console.log(stepDescArr[i].rule)
                    if (totalPrice >= stepDescArr[i].rule) {
                        //计算总优惠金额
                        let totalDiscountPrice = stepDescArr[i].reduction
                        //计算 除最后一个商品的 活动优惠金额总合 
                        let totalActiveDiscountExcludeLast = calculateTotalActiveDiscountExcludeLast(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice)
                        //计算每个品的 活动优惠  
                        let mapGoods = calculateEveryGoodsDiscount(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice, totalActiveDiscountExcludeLast)

                        unPriceTypeDiscount = NP.plus(unPriceTypeDiscount, totalDiscountPrice)
                        addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `满${stepDescArr[i].rule} 减${totalDiscountPrice}`, discountPrice: totalDiscountPrice })
                        break   //阶梯 跳出循环
                    }
                }

            }

        } else if (type === '4') { //阶梯件数满减
            //console.log(`'阶梯件数满减！`)
            const useUser = foundActivity.useUser
            if (isUserStatusValid(useUser, currentMemberInfo.value)) {
                //查找阶梯明细
                const stepDescArr = discountStep.value.filter(item => item.activityID === foundActivity.activityID)
                let totalPiece = calculateGroupGoodsTotalPiece(unPriceGroupDataObj[key])
                for (let i = stepDescArr.length - 1; i >= 0; i--) { //倒序循环阶梯
                    if (totalPiece >= stepDescArr[i].rule) {
                        let totalPrice = calculateActivityGroupTotalPrice(unPriceGroupDataObj[key])
                        //计算总优惠金额
                        let totalDiscountPrice = stepDescArr[i].reduction
                        //计算 除最后一个商品的 活动优惠金额总合 
                        let totalActiveDiscountExcludeLast = calculateTotalActiveDiscountExcludeLast(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice)
                        //计算每个品的 活动优惠  
                        let mapGoods = calculateEveryGoodsDiscount(unPriceGroupDataObj[key], totalPrice, totalDiscountPrice, totalActiveDiscountExcludeLast)

                        unPriceTypeDiscount = NP.plus(unPriceTypeDiscount, totalDiscountPrice)
                        addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `满${stepDescArr[i].rule}件 减${totalDiscountPrice}`, discountPrice: totalDiscountPrice })
                        break   //阶梯 跳出循环
                    }
                }

            }

        } else if (type === '11') { //赠品
            //console.log(`'赠品`)
            //console.log(unPriceTypeDiscount)
            const useUser = foundActivity.useUser
            if (isUserStatusValid(useUser, currentMemberInfo.value)) {
                //查找赠品明细
                const giftDescArr = goodsGift.value.filter(item => item.activityID === foundActivity.activityID)
                let giftText = '[' + giftDescArr.map(item => item.goodsName + "*" + item.quantity).join(' 或 ') + ']'
                const rule = foundActivity.rule
                let totalPrice = calculateActivityGroupTotalPrice(unPriceGroupDataObj[key])
                //  console.log(totalPrice)

                if (rule === 0 || totalPrice >= rule) { //满足赠品规则，在选择赠品弹窗添加选项
                    currentGoodsGiftAndActivitys.value.push({ activity: foundActivity, giftDescArr, currentPage: 1 })
                } else { //不满足 删除已选赠品
                    //    console.log(shoppingCarData.value[currentActiveVariableIndex.value])
                    const findIndex = shoppingCarData.value[currentActiveVariableIndex.value].findIndex(item => item.activityID === foundActivity.activityID && item.isGift)
                    if (findIndex != -1) {//选过赠品了 则删除
                        shoppingCarData.value[currentActiveVariableIndex.value].splice(findIndex, 1)
                    }
                }

                let giftDiscount = 0 //赠品总优惠金额
                //查找当前活动 已选赠品
                // console.log( shoppingCarData.value[currentActiveVariableIndex.value])
                // console.log(foundActivity)
                const currentSelectedGift = shoppingCarData.value[currentActiveVariableIndex.value].find(item => item.activityID === foundActivity.activityID && item.isGift)
                //console.log(currentSelectedGift)

                if (currentSelectedGift) { //如果选择了赠品，则计算优惠
                    giftDiscount = roundNumber(NP.times(currentSelectedGift.basicPrice, currentSelectedGift.quantity))
                    // console.log(giftDiscount)

                    //计算 除最后一个商品的 活动优惠金额总合 每个品按该商品金额占该活动总金额的 比例分配优惠 （某商品总金额/当前活动总金额 * 总优惠金额）
                    let totalActiveDiscountExcludeLast = calculateTotalActiveDiscountExcludeLast(unPriceGroupDataObj[key], totalPrice, giftDiscount)
                    //计算每个品的 活动优惠 
                    // console.log(unPriceGroupDataObj[key])
                    // let mapGoods = calculateEveryGoodsDiscount(unPriceGroupDataObj[key], totalPrice, giftDiscount, totalActiveDiscountExcludeLast)
                    // console.log(currentSelectedGift.value)
                    let mapGoods = unPriceGroupDataObj[key].map(item => ({ ...item, activityDiscount: giftDiscount }))
                    unPriceTypeDiscount = NP.plus(unPriceTypeDiscount, giftDiscount)
                    // console.log(unPriceTypeDiscount)
                    if (rule === 0) { //无门槛赠
                        //  console.log('无门槛赠')
                        addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `无门槛 赠${giftText}`, discountPrice: giftDiscount })
                    } else {
                        if (totalPrice >= rule) {

                            addActivityDiscountLog({ activity: foundActivity, goods: mapGoods, type: activityTypeObj[type], text: `满${rule} 赠${giftText}`, discountPrice: giftDiscount })
                        }
                    }
                }


            }

        }


    }

    // console.log('其它活动优惠：', unPriceTypeDiscount)

    currentTotalActivityDiscount.value = NP.plus(priceTypeDiscount, unPriceTypeDiscount)
    unPriceTypeDiscountTotal.value = unPriceTypeDiscount
    // console.log(currentTotalActivityDiscount.value)
    return currentTotalActivityDiscount.value
}


//按key 分组 {key1:[],key2:[],...}
function groupByKey(list, key) {
    let obj = {}
    for (let item of list) {
        if (!obj[item[key]]) {
            obj[item[key]] = []
        }
        obj[item[key]].push(item);
    }
    return obj
}


//赠品分页后的数据
const pageGiftData = computed(() => {
    return (goods) => {
        return paginateData(goods, 3) || [] //赠品 每页6条数据
    }

})

//选择赠品
function chooseGift(item) {
    currentSelectGoodsGift.value = item
}
//确定选择赠品
function confirmChooseGift() {
    const gift = currentSelectGoodsGift.value
    //console.log(gift)
    if (gift) {
        let basicPrice = 0
        let retailPrice = 0
        //查找赠品价格
        const goods = currentPriceTypeGoodsData.value[0]?.posSaleGoodsPriceVos || []
        //console.log(goods)
        if (goods.length >= 0) {
            const found = goods.find(item => item.goodsID === gift.goodsID)
            // console.log(found)
            if (found) {
                basicPrice = found.basicPrice
                retailPrice = found.basicPrice
            }
        }
        // console.log(basicPrice)

        //如果是相同活动下的赠品，则更新赠品数据 ，否则添加一条赠品信息
        const index = shoppingCarData.value[currentActiveVariableIndex.value].findIndex(item => item.activityID === gift.activityID) //相同活动
        if (index === -1) {

            shoppingCarData.value[currentActiveVariableIndex.value].unshift({ isGift: true, ...gift, basicPrice, retailPrice, currentTime: currentTime.value })
        } else {
            shoppingCarData.value[currentActiveVariableIndex.value].splice(index, 1, { isGift: true, ...gift, basicPrice, retailPrice, currentTime: currentTime.value })
        }




    }
    giftDialogVisible.value = false
}



//打印小票
async function printTicket({ type, orderNum }) {
    if (type === 'order') { //结算 创建订单
        JsBarcode("#barcode", orderNum, {
            format: "CODE128", // 可以选择其他格式，如 "EAN13"、"UPC" 等
            lineColor: "#000", // 条形码颜色
            width: 2.5,          // 条宽
            height: 100,       // 条高
            displayValue: false // 是否显示数值
        });
        nextTick(() => {
            getDomToImg({ dom: createOrderPrintRef.value, type, orderNum })
        })

    } else if (type === 'recharge') {
        nextTick(() => {
            getDomToImg({ dom: rechargePrintRef.value, type, orderNum })
        })
    }






}


//清理操作，清理购物车数据 关闭弹窗等
function clearData() {
    //清空当前购物车
    shoppingCarData.value[currentActiveVariableIndex.value] = []
    isShowPayKeyboard.value = false
    if (authCode.value) { //清除扫码值
        authCode.value = null
    }
    if (isShowElectronicDialog.value) {
        isShowElectronicDialog.value = false
    }
    //清空已选优惠券
    currentSelectCoupon.value = null
    //清除当前使用优惠券
    currentUsingCoupon.value = null
    //清除优惠券抵扣金额
    currentCouponDiscountPrice.value = 0
    //退出登录
    currentMemberInfo.value = null
    currentTelPhone.value = ''
    //清空支付方式
    payTypeTable.value = []

}


//dom-to-image
async function getDomToImg({ dom, type, orderNum }) {

    try {
        const dataUrl = await domtoimage.toPng(dom)
        const base64ImageData = dataUrl.replace(/^data:image\/png;base64,/, '');
        await window.electron.ipcRenderer.invoke('send-print', { data: base64ImageData })
    } catch (error) {
        console.error('domtoimage something wrong!', error);
    } finally {
        if (type === 'order') {

            clearData()


        } else if (type === 'recharge') { //充值

        }
    }

    // console.log(dom)
    // domtoimage.toPng(dom)
    //     .then(function (dataUrl) {
    //         // console.log(dataUrl)
    //         const base64ImageData = dataUrl.replace(/^data:image\/png;base64,/, '');
    //        await window.electron.ipcRenderer.invoke('send-print', { data: base64ImageData })

    //     })
    //     .catch(function (error) {
    //         console.error('domtoimage something wrong!', error);
    //     }).finally(() => {
    //         if (type === 'order') {
    //             //清空当前购物车
    //             shoppingCarData.value[currentActiveVariableIndex.value] = []
    //             isShowPayKeyboard.value = false
    //             if (authCode.value) { //清除扫码值
    //                 authCode.value = null
    //             }
    //             if (isShowElectronicDialog.value) {
    //                 isShowElectronicDialog.value = false
    //             }
    //             //清空已选优惠券
    //             currentSelectCoupon.value = null
    //             //清除当前使用优惠券
    //             currentUsingCoupon.value = null
    //             //清除优惠券抵扣金额
    //             currentCouponDiscountPrice.value = 0
    //             //退出登录
    //             currentMemberInfo.value = null
    //             currentTelPhone.value = ''
    //             //清空支付方式
    //             payTypeTable.value = []



    //         } else if (type === 'recharge') { //充值

    //         }
    //     });


}

//生成离线订单id（时间戳+店铺id+2位随机数）
function getOfflineId() {

    const timeStr = currentTime.value
    /*生成2位随机数*/
    const array = new Uint8Array(1);          // 创建1字节（8位）的无符号数组
    window.crypto.getRandomValues(array);     // 用加密安全随机数填充数组（值范围0-255）
    const num = array[0] % 100;              // 取模运算映射到0-99范围
    const randomStr = num.toString().padStart(2, '0');
    /*生成2位随机数结束*/
    return timeStr + shopID.toString() + randomStr
}

</script>


<style lang='scss'>
.custom_select {

    .el-select-dropdown__item {

        line-height: 50px;
        height: 50px;

    }
}
</style>
<style scoped lang='scss'>
.nav_right {
    display: flex;
    align-items: center;


}

.wrap {
    display: flex;
    height: 100%;
    box-sizing: border-box;
    background-color: var(--ev-c-white);
    border-radius: 10px;
    overflow: hidden;

    .left {
        width: 36%;
        box-sizing: border-box;
        // padding: 0 10px;

        .left_container {
            // border-right: 1px solid #ccc;
            height: 100%;
            box-sizing: border-box;

            position: relative;

            .member {
                padding: 5px 0 5px 5px;
                height: 95px;
                box-sizing: border-box;

                .member_info {
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;
                    height: 100%;

                    .top {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;

                        .flex {
                            display: flex;
                            align-items: center;
                        }
                    }

                    .bottom {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;

                        .left {
                            height: 40px;
                            line-height: 40px;
                            flex: 1;
                            display: flex;
                            align-items: center;

                            .coupon {
                                margin-left: 10px;
                            }

                            .num {
                                color: var(--el-color-danger);
                                font-weight: bold;
                            }
                        }

                    }
                }

                .telphone {
                    position: relative;

                    :deep(input) {
                        height: 83px;
                        line-height: 83px;
                        font-size: 20px;
                    }

                }



            }

            .table_wrap {
                margin-left: 5px;
                // margin-bottom: 10px;
                height: calc(100% - 95px - 101px - 40px - 5px);
                border: 1px solid var(--el-border-color);
                border-bottom: 0;
                box-sizing: border-box;

                .empty_wrap {
                    height: calc(100vh - 50px - 95px - 40px - 5px - 40px - 101px - 14px);
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    box-sizing: border-box;
                    overflow: hidden;

                    :deep(.el-empty) {
                        padding: 0;
                        height: 100%;
                        overflow: hidden;
                    }
                }

                .my_table {
                    width: 100%;
                    height: 100%;

                    .table_header {
                        display: flex;

                        &>div {
                            flex: 1;
                            width: 33.33%;
                        }
                    }

                    .goods_name {
                        color: var(--el-text-color-primary);

                        :deep(.el-tag) {
                            vertical-align: baseline;
                            margin-right: 2px;
                            padding: 0 5px;
                        }
                    }

                    .row {
                        display: flex;

                        &>div {
                            flex: 1;
                            width: 33.33%;
                        }

                        .red {
                            color: var(--el-color-danger);
                            // font-weight: bold;
                        }

                    }
                }


            }

            .btns_group {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding-left: 5px;
                margin-bottom: 5px;

                :deep(.el-button) {
                    flex: 1;

                    max-width: 20%;
                }

                :deep(.el-button+.el-button) {
                    margin-left: 0;

                }
            }

            .left_bottom {
                width: 100%;
                position: absolute;
                left: 0;
                bottom: 0px;

                .total_price {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    // padding: 0 0 10px 5px;
                    padding-left: 5px;
                    height: 60px;

                    // border-bottom: 1px solid #ccc;
                    // border-top: 1px solid #ccc;
                    :deep(.el-button) {
                        height: 50px;
                        width: 100px;
                        margin-left: 5px;
                    }

                    .left {
                        flex: 1;
                        display: flex;
                        flex-direction: column;
                        justify-content: space-between;

                        &>span {
                            font-size: 14px;
                            background-color: var(--el-color-danger);
                            border-radius: 4px;
                            color: #fff;
                            padding: 2px 5px;
                        }

                        &>div {
                            line-height: 26px;
                            height: 26px;
                            font-size: 18px;
                            padding-left: 5px;
                        }
                    }
                }

                .varible_container {
                    display: flex;
                    border-top: 1px solid var(--el-color-primary);

                    .mark {
                        flex: 1;
                    }

                    .item {
                        flex: 1;
                        line-height: 40px;
                        height: 40px;
                        text-align: center;
                        border-right: 1px solid var(--el-color-primary);

                        // &:last-child{
                        //     border-right: none;
                        // }
                        &.active {
                            background-color: var(--el-color-primary);
                            color: #fff;
                        }

                    }

                }
            }
        }

    }

    .right {
        width: calc(64% - 5px);
        padding: 5px 0 0 5px;

        box-sizing: border-box;

        .right_top {
            display: grid;
            // align-items: center;
            margin-bottom: 5px;
            grid-template-columns: 3fr 2fr 2fr;
            gap: 5px;

            .item {
                line-height: 40px;
                height: 40px;

                span {
                    font-size: 20px;
                }

                .num {
                    color: var(--el-color-danger);

                }
            }
        }

        .goods_group {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 5px;

            .page_btn {
                height: 85px;
                width: 46px;

                &.prev {
                    margin-right: 4px;
                }

                &.next {
                    margin-left: 4px;
                }
            }

            .list {
                flex: 1;
                display: grid;
                gap: 5px;
                grid-template-rows: repeat(2, 1fr);
                grid-template-columns: repeat(5, minmax(100px, 1fr));

                .group_name {
                    color: #000;
                    font-size: 16px;
                }

                .active {
                    color: #fff;
                }

                :deep(.el-button) {
                    // border-radius: 0;
                    // border: none;
                    white-space: break-spaces;
                }

                :deep(.el-button+.el-button) {
                    margin-left: 0;

                }
            }
        }

        .goods_list {
            height: calc(100% - 45px - 90px);
            padding: 2px;
            overflow: hidden;
            box-sizing: border-box;
            display: grid;
            gap: 2px;
            grid-template-rows: repeat(6, 1fr);
            grid-template-columns: repeat(5, 1fr);
            background-color: var(--el-color-primary);

            .item {
                text-indent: 5px;
                background-color: var(--ev-c-white);
                box-sizing: border-box;
                // border: 1px solid #ccc;
                // border-radius: 2px;
                padding: 2px;
                display: flex;
                flex-direction: column;
                justify-content: space-between;

                .goods_name {
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 2;
                    overflow: hidden;

                    :deep(.el-tag) {
                        vertical-align: baseline;
                        margin-right: 2px;
                        padding: 0 5px;
                    }

                }

                .info {
                    font-size: 12px;
                    text-align: right;

                    .price {
                        color: var(--el-color-danger);
                        font-weight: bold;
                    }
                }

                &.active {
                    background-color: var(--el-color-primary-light-7);
                }
            }

        }

        .empty {
            height: calc(100% - 45px - 90px);
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }
}

.recharge_dialog {

    //充值活动
    .activity_list {
        display: grid;
        flex-wrap: wrap;
        margin-bottom: 10px;
        grid-template-columns: repeat(5, 1fr);
        gap: 10px;

        .item {

            padding: 10px;
            border: 1px solid #ccc;

            .capital {
                font-size: 16px;
            }

            .desc {
                color: var(--el-color-info);
            }
        }

        .active {
            background-color: var(--el-color-primary);
            color: #fff;
            font-weight: bold;

            .desc {
                color: #fff;
            }
        }


    }

    .pay_type {
        display: flex;

        :deep(.el-button) {
            flex: 1;
        }
    }
}

.pay_top {
    display: flex;
    align-items: center;
    width: 100%;
    box-sizing: border-box;
    padding-right: 5px;
    justify-content: space-between;
    margin-bottom: 10px;

    .left {
        display: flex;
        align-items: center;
        width: 100%;

        .row {
            flex: 1;
            display: flex;
            align-items: center;
            line-height: 40px;
            font-size: 16px;

            &>span {
                padding-right: 10px;
            }
        }
    }

    .right {
        display: flex;
        align-items: center;
        width: 100%;
    }

}

.pay_left {
    margin-right: 5px;
    height: 309px;
    overflow-y: auto;
}

.pay_type_wrap {
    margin-top: 10px;
    display: flex;
    align-items: center;
    width: 100%;

    .page_btn {
        height: 85px;

        &.prev {
            margin-right: 10px;
        }

        &.next {
            margin-left: 10px;
        }
    }
}

.pay_type_list {
    flex: 1;

    display: grid;
    grid-template-rows: repeat(2, 1fr);
    grid-template-columns: repeat(6, minmax(100px, 1fr));
    gap: 5px;
    overflow: hidden;

    .item {
        margin-left: 0;
        width: 100%;

        :deep(span) {

            display: -webkit-box !important;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            white-space: break-spaces;
            overflow: hidden;
        }

    }

}

.pay_input {
    :deep(input) {
        &::selection {
            background-color: var(--el-color-primary);
            color: #fff;
        }
    }

}

//输入框选中样式
.select {
    :deep(>span) {
        background-color: var(--el-color-primary) !important;
        color: #fff !important;
    }
}

/*赠品弹窗*/
.gift_dialog_main {
    .activity_name {
        font-size: 16px;
    }

    .goods_wrap {
        display: flex;
        width: 100%;
        margin: 10px 0;

        .page_btn {
            height: 40px;

            &.prev {
                margin-right: 10px;
            }

            &.next {
                margin-left: 10px;
            }
        }

        .goods_list {
            flex: 1;
            display: grid;
            grid-template-columns: repeat(3, minmax(180px, 1fr));
            gap: 10px;

            :deep(.el-button) {
                white-space: break-spaces;
            }
        }
    }

}

/*优惠券弹窗*/
.copon_dialog_main {
    .title {
        font-size: 16px;
        color: var(--el-text-color-primary);
        padding: 10px 0;
    }

    .usable_coupon_wrap,
    .unusable_coupon_wrap {
        display: flex;
        width: 100%;

        .page_btn {
            height: 144px;

            &.prev {
                margin-right: 10px;
            }

            &.next {
                margin-left: 10px;
            }
        }
    }

    .unusable_coupon_wrap {
        .page_btn {
            height: 67px;
        }
    }

    .usable_coupon_list,
    .unusable_coupon_list {
        opacity: .6;
        flex: 1;
        display: grid;
        grid-template-columns: repeat(2, 1fr);

        gap: 10px;
    }

    .usable_coupon_list {
        grid-template-rows: repeat(2, 1fr);
    }


    .usable_coupon_list {
        opacity: 1;
    }

    .coupon_item {

        display: flex;
        border: 1px solid var(--el-border-color);
        padding: 10px;
        box-sizing: border-box;

        &.active {
            background-color: var(--el-color-primary);
            color: #fff;

            .left {
                .discount_text {

                    color: #fff;
                }
            }

            .right {
                .time {
                    color: #fff;
                }
            }
        }

        .left {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            width: 200px;
            width: 100px;

            .discount_text {
                font-size: 20px;
                color: var(--el-color-danger);
            }

            .type_text {
                font-size: 14px;

            }

        }

        .right {
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .time {
                color: var(--el-color-info);
            }
        }
    }
}


//打印相关
.print_wrap {
    .title {
        text-align: center;
        line-height: 1.5;
        font-size: 38px; //临时修改
    }

    background-color: #fff;

    color: #000;


    width:800px; //这里一定设置为800px 经过测试后的合适距离

    box-sizing:border-box;
    // font-weight: bold;
    // font-size:36px;
    font-size: 36px;
    position: absolute;
    top: 0;
    left:0;
    z-index: -10;

    .line {
        width: 100%;
        border-top: 1px dashed #000;
        height: 1px;
        margin: 15px 0;
    }

    .margin_bottom_placeholder {
        //这里使用空div 站位 下边距
        width: 100%;
        height: 400px;

    }

    .flex {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .discount {
        text-align: right;
    }
}

//托利多字体稍小
.tuoliduo {
    .title {
        font-size: 28px !important;
    }

    font-size:26px !important;
}

/*
会员电子支付
*/
.electronic_recharge_dialog_main,
.electronic_dialog_main {
    text-align: center;
    font-size: 16px;

    .row {
        padding: 15px 0;
    }

    .money {
        font-size: 20px;
        line-height: 50px;
    }
}

/*重量商品 选择商品弹窗*/
.selectgoods_dialog_title {
    font-size: 20px;
    color: var(--el-text-color-primary);
    text-align: center;
}

.selectgoods_dialog_main {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;

    .flex {
        display: flex;
        align-items: center;
        font-size: 18px;
        padding: 10px 0;
        width: 250px;
        text-align: center;
        width: 51%;

        .label {
            margin-right: 40px;
        }
    }
}

.selectgoods_dialog_footer {
    display: flex;

    :deep(.el-button) {
        flex: 1;
    }
}
</style>